The format of the API Builder Data Connector API Response looks similar to this:
{
"success": true,
"request-id": "9803004a-253b-4a2a-ad9a-f5ad9ece4479",
"key": "employees",
"employees": [
{
"id": "60254151dbfceb01888d6685",
"fname": "Jane",
"lname": "Doe",
"title": "CFO"
},
.
.
.
{
"id": "6025413d94333f01894ed371",
"fname": "Leor",
"lname": "Brenman",
"title": "SE"
}
]
}
The actual data is in the property referenced by the key. In the example above this is the employees’ property, but will depend on the name of your model/table/collection.
However, you may prefer an output that simply contains your data as follows:
[
{
"id": "60254151dbfceb01888d6685",
"fname": "Jane",
"lname": "Doe",
"title": "CFO"
},
.
.
.
{
"id": "6025413d94333f01894ed371",
"fname": "Leor",
"lname": "Brenman",
"title": "SE"
}
]
An easy way to achieve this is to add a post block to your model(s).
For example, consider the following post block, /blocks/formatoutput.js:
var APIBuilder = require('@axway/api-builder-runtime');
var formatoutput = APIBuilder.Block.extend({
name: 'formatoutput',
description: 'format output',
action: function (req, resp, next) {
let body = JSON.parse(resp.body)
resp.status('200');
resp.send(body[body.key]);
next();
}
});
module.exports = formatoutput;
The post block replaces the response body with just the data.
You attach this to your model using the after the property as follows:
var APIBuilder = require('@axway/api-builder-runtime');
var Model = APIBuilder.createModel('employee', {
"connector": "mbs",
"fields": {
"fname": {
"type": "string"
},
"lname": {
"type": "string"
},
"title": {
"type": "string"
}
},
"after": "formatoutput",
"actions": [
"create",
"read",
"update",
"delete",
"deleteAll"
]
});
module.exports = Model;
Note the line
"after": "formatoutput",
above.
Summary
API Builder makes it easy to adapt APIs to meet your needs. In this example, we saw how to use a post block to format the response of a data connector API call.
Read more about creating an API Builder Custom API that acts as a Webhook for Twilio.