HTTP requests
Call other HTTP services with RESTBuilder, REQUEST() and DOWNLOAD().
On this page
Total.js has three tools for calling other HTTP services from your application:
RESTBuilderbuilds a request step by step, sends it and parses the answer (JSON, XML or URL-encoded). Use it for REST APIs.REQUEST(options, [callback])is the low-level HTTP client thatRESTBuilderuses. It returns the raw body, or a stream.DOWNLOAD(url, filename, [callback], [timeout])saves a response straight into a file.
All three are global: you can use them in controllers, schemas, definitions and modules without require().
RESTBuilder
A static method creates the builder for the HTTP method you need. The data you pass to POST, PUT, PATCH and DELETE is sent as JSON; the data of GET becomes the query string.
RESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {
if (err) {
console.log('Error:', err);
return;
}
console.log(response); // the parsed body
console.log(output.status); // the HTTP status code
});
RESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {
console.log(response);
});The callback receives three arguments:
| Argument | What it contains |
|---|---|
err | An error, or null |
response | The parsed body: an object for JSON, XML and URL-encoded answers, otherwise an empty object |
output | Details: value, response (the raw body), status, headers, hostname, origin, cache and the method cookie(name) |
A status code 400 or higher is not an error by default: check output.status, or call strict() to get the status code as err. When the service answers with a Total.js error array ([{ name, error }]), err is an ErrorBuilder with those errors.
Promises
promise() sends the request and returns a promise of the parsed body. Pass $ (the options of a schema operation) and the error goes to $.invalid() instead of rejecting the promise.
NEWSCHEMA('Weather', function(schema) {
schema.action('current', {
name: 'Current weather',
action: async function($) {
var data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);
$.callback(data);
}
});
});callback() without a function also returns a promise.
Building the request
Every method returns the builder, so you can chain them. Nothing is sent until you call callback(), exec(), promise() or stream().
RESTBuilder.make(function(builder) {
builder.url('https://api.example.com/invoices/');
builder.method('POST');
builder.header('X-Token', CONF.token);
builder.auth('user', 'password');
builder.timeout(5000);
builder.json({ number: '2024001', total: 120 });
builder.callback(function(err, response, output) {
console.log(output.status, response);
});
});| Area | Methods |
|---|---|
| Address and method | url(), method(), get(), post(), put(), patch(), delete(), head() |
| Headers | header(), type(), accept(), auth(), referrer(), xhr() |
| Body | json(), urlencoded(), xml(), plain(), raw(), set(), rem(), file() |
| Cookies | cookie(), cookies(), cook() |
| Connection | timeout(), keepalive(), proxy(), cert(), insecure(), nodnscache(), redirect(), unixsocket() |
| Response | strict(), noparse(), schema(), map(), convert(), cache(), progress() |
| Sending | callback(), exec(), promise(), stream() |
The default timeout is 10 seconds. The builder sends User-Agent: Total.js/v... and accepts JSON, text and XML.
Uploading files
file() adds a file and switches the request to multipart/form-data (a GET becomes a POST). The content can be a path, a Buffer or a URL that the framework downloads and forwards. set() adds plain form fields.
RESTBuilder.POST('https://api.example.com/upload/')
.file('file', 'report.pdf', PATH.databases('report.pdf'))
.set('folder', 'reports')
.callback(function(err, response) {
console.log(err, response);
});Shaping the response
schema(name)validates the response with a schema and returns the model. A status code400or higher is an error here.map('id:number,name:string')keeps only the listed fields and converts them;id:number:itemidalso renamesidtoitemid.convert('price:number,date:date')converts fields of the response withCONVERT().cache('5 minutes')caches a successful (200) response inF.cache.
RESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {
// users === [{ id: 1, name: 'Peter' }, ...]
});Calling Total.js API endpoints
RESTBuilder.API(url, operation, [data]) sends a POST with the JSON { schema: operation, data: data }, the format of Total.js API routes:
RESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {
console.log(response);
});Global changes
RESTBuilder.upgrade(fn) runs fn(builder) for every builder before it sends the request, for example to add a header to all requests. RESTBuilder.addTransform(name, fn, [isDefault]) registers a function that changes every parsed response.
REQUEST()
REQUEST(options, [callback]) sends one HTTP request. The body you send must be a string or a Buffer; the response body is a string for text and application/* types, otherwise a Buffer. Without a callback it returns a promise.
REQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {
if (err)
return;
console.log(response.status, response.headers, response.body);
});
var response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });With custom: true you get response.stream (the incoming message) instead of the body. The framework follows 301 and 302 redirects and copies their cookies to the next request; noredirect: true turns that off.
DOWNLOAD()
DOWNLOAD(url, filename, [callback], [timeout]) writes the response into a file. A relative URL (/sitemap.xml) is requested from your own running application.
DOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
console.log(err, response.status);
});Proxy
CONF.default_proxy sends every request through a proxy server, except requests to localhost, 127.0.0.1 and 0.0.0.0. proxy(url) and the proxy option set a proxy for one request. The value can contain credentials: http://user:password@proxy.example.com:8080.
The configuration key default_restbuilder_timeout (default 10000) is the timeout of REQUEST() calls without their own timeout.