Call other HTTP APIs with RESTBuilder
RESTBuilder.GET(url), .POST(url, data), .PUT, .PATCH and .DELETE build a request. Data of a POST is sent as JSON. Chain .header(name, value), .cookie(name, value), .timeout(milliseconds) and .auth(user, password) before .exec(function(err, response, output) {}) (or .promise() for await).
responseis the body, parsed automatically when it is JSONoutput.statusis the HTTP status andoutput.headersthe response headerserris set for network errors and for HTTP error statuses
The example calls two routes of its own app so it can run anywhere; use the address of the real service in your code. $.hostname(path) builds the full URL of this server.
exports.install = function() {
ROUTE('GET /api/hello/', hello);
ROUTE('POST /api/sum/', sum);
ROUTE('GET /call/', call);
};
function hello($) {
$.json({ message: 'hello', agent: $.headers['x-agent'] || null });
}
function sum($) {
$.json({ sum: $.body.a + $.body.b });
}
async function call($) {
var greeting = await RESTBuilder.GET($.hostname('/api/hello/')).header('x-agent', 'forge').timeout(5000).promise();
var total = await RESTBuilder.POST($.hostname('/api/sum/'), { a: 20, b: 22 }).promise();
RESTBuilder.GET($.hostname('/api/missing/')).exec(function(err, response, output) {
$.json({ greeting: greeting, total: total, missing: output.status });
});
}