---
title: HTTP requests
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/http-requests/
updated: 2026-11-16T15:57:56.811Z
---

# HTTP requests

> RESTBuilder, REQUEST() and DOWNLOAD(): the clients for other HTTP services.

The global functions and the `RESTBuilder` methods that send requests to other services. The guide [HTTP requests](../../guides/http-requests/) explains how to use them with examples; this page is the exact reference.

## API

### REQUEST(options, [callback])

Type: `method`

Sends an HTTP request and returns the raw response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes |  | The options of the request (see the table). |
| `callback` | `Function` | no |  | `function(err, response)`. Without it the method returns a promise. |

Returns: `Promise|undefined` A promise of the response when you do not pass a callback.

The low-level HTTP client of the framework; `RESTBuilder` and `DOWNLOAD()` use it. Without a callback it returns a promise of the response.

**Options**

| Option | Type | Description |
| --- | --- | --- |
| `url` | String | The address (`http://` or `https://`) |
| `method` | String | The HTTP method, default `GET` |
| `headers` | Object | Request headers |
| `query` | Object/String | Appended to the URL as a query string |
| `body` | String/Buffer | The body; with `files`, an object of form fields |
| `type` | String | Sets `Content-Type`: `json`, `urlencoded`, `xml`, `plain`, `html` or `raw` (`application/octet-stream`) |
| `files` | Array | Files to upload as `multipart/form-data`: `{ name, filename, buffer }`, `{ name, filename, path }` or `{ name, filename, url }` |
| `cookies` | Object | Cookies to send, as `{ name: value }` |
| `cook` | Boolean | Collects cookies of the responses (also from redirects) into `options.cookies` |
| `timeout` | Number | Milliseconds; default `CONF.default_restbuilder_timeout` (`10000`); `0` turns it off |
| `encoding` | String | Encoding of a text response, default `utf8`; `binary` returns a `Buffer` |
| `custom` | Boolean | Returns `response.stream` instead of reading the body |
| `noredirect` | Boolean | Does not follow `301` and `302` redirects |
| `keepalive` | Boolean | Reuses connections (not with a proxy) |
| `proxy` | String | A proxy server, for example `http://user:pass@host:8080` |
| `resolve` / `dnscache` | Boolean | Resolves the host name once and caches the address |
| `xhr` | Boolean | Adds `X-Requested-With: XMLHttpRequest` |
| `unixsocket` | Object | `{ socket, path }` sends the request to a Unix socket instead of `url` |
| `key`, `cert`, `dhparam` | Buffer | TLS client certificate |
| `insecure` | Boolean | Accepts invalid TLS certificates |
| `compress` | String | Compresses the body with `gzip` or `deflate` and sets `Content-Encoding` |
| `encrypt` | String | Encrypts the body with this key (header `X-Encryption`) and decrypts a text response |
| `onprogress` | Function | `fn(percentage)` while the body downloads |
| `ondata` | Function | `fn(chunk, percentage)` for every chunk |
| `callback` | Function | The same as the `callback` argument |

**Response**: `status`, `headers`, `body`, `host`, `origin` (the resolved addresses, with `resolve`) and `cookies`; with `custom: true`, `stream` instead of `body`. Errors: `Invalid hostname`, the text of status `408` after a timeout, `Too many redirects` after four redirects, or a network error (then `status` is `0`).

Example: GET with a callback
```js
REQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {
	if (err) {
		console.log(err);
		return;
	}
	console.log(response.status, response.body);
});
```

Example: POST JSON with a promise
```js
var response = await REQUEST({
	url: 'https://api.example.com/items/',
	method: 'POST',
	type: 'json',
	body: JSON.stringify({ name: 'Item' })
});
var data = response.body.parseJSON();
```

Example: Read a stream
```js
REQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {
	if (!err)
		response.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));
});
```

### DOWNLOAD(url, filename, [callback], [timeout])

Type: `method`

Downloads a URL into a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Object` | yes |  | An absolute or relative URL, or `{ socket, path }`. |
| `filename` | `String` | yes |  | The target file. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Milliseconds. |

Returns: `Promise|undefined` A promise of the response when you do not pass a callback.

Sends a `GET` request and writes the response body into `filename`. The callback runs when the file is written. Without a callback the method returns a promise.

A relative URL (for example `/sitemap.xml`) is requested from your own application; before the application is loaded the call waits. An object `{ socket, path }` instead of the URL sends the request to a Unix socket.

The response has `status`, `headers` and `filename`. The status code is not checked: the file is written for `404` too.

Example: Save an image
```js
DOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
	if (err || response.status !== 200)
		console.log('Download failed');
});
```

Example: With await
```js
var response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);
```

### RESTBuilder.GET(url, [data])

Type: `method`

Creates a builder for a `GET` request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address. |
| `data` | `Object` | no |  | Query string arguments. |

Returns: `RESTBuilder` A new builder.

`data` becomes the query string of the URL. Send the request with `callback()`, `exec()`, `promise()` or `stream()`.

Example: Load a list
```js
RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {
	// GET https://api.example.com/products/?page=2&limit=50
	console.log(response);
});
```

### RESTBuilder.POST(url, [data])

Type: `method`

Creates a builder for a `POST` request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address. |
| `data` | `Object` | no |  | The body, sent as JSON. |

Returns: `RESTBuilder` A new builder.

The data is sent as JSON. Call `urlencoded()` or `xml()` to send another format.

Example: POST request
```js
RESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
```

### RESTBuilder.PUT(url, [data])

Type: `method`

Creates a builder for a `PUT` request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address. |
| `data` | `Object` | no |  | The body, sent as JSON. |

Returns: `RESTBuilder` A new builder.

The data is sent as JSON.

Example: PUT request
```js
RESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
```

### RESTBuilder.PATCH(url, [data])

Type: `method`

Creates a builder for a `PATCH` request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address. |
| `data` | `Object` | no |  | The body, sent as JSON. |

Returns: `RESTBuilder` A new builder.

The data is sent as JSON.

Example: PATCH request
```js
RESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
```

### RESTBuilder.DELETE(url, [data])

Type: `method`

Creates a builder for a `DELETE` request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address. |
| `data` | `Object` | no |  | The body, sent as JSON. |

Returns: `RESTBuilder` A new builder.

The data, if any, is sent as JSON.

Example: DELETE request
```js
RESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
```

### RESTBuilder.HEAD(url)

Type: `method`

Creates a builder for a `HEAD` request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address. |

Returns: `RESTBuilder` A new builder.

Read the answer from `output.status` and `output.headers` in the callback.

Example: Does the file exist?
```js
RESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {
	console.log(output.status === 200, output.headers['content-length']);
});
```

### RESTBuilder.API(url, name, [data])

Type: `method`

Calls an operation of a Total.js API endpoint.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The address of the API endpoint. |
| `name` | `String` | yes |  | The name of the operation, with its parameters (for example `products_read/P01`). |
| `data` | `Object` | no |  | The data of the operation. |

Returns: `RESTBuilder` A new builder.

Sends a `POST` with the JSON body `{ schema: name, data: data }`, the format that Total.js API routes read.

Example: Call an operation
```js
RESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {
	console.log(err, response);
});
```

### RESTBuilder.make(fn)

Type: `method`

Creates an empty builder and passes it to a function.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(builder)`. |

Returns: `RESTBuilder` The new builder.

`fn(builder)` sets the URL, method and everything else. `RESTBuilder.url(url)` creates a builder with a URL only, and the instance method `builder.make(fn)` calls `fn` with the builder as `this` and as the argument.

Example: Build the request
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/orders/');
	builder.post({ product: 'P01' });
	builder.header('X-Token', CONF.token);
	builder.callback(console.log);
});
```

### RESTBuilder.upgrade(fn)

Type: `method`

Changes every builder before it sends its request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(builder)`. |

Returns: `undefined`

`fn(builder)` runs in `exec()` for every builder of the application, after the body is prepared and before the request is sent. Register it once, in a definition file.

Example: Add a header to all requests
```js
// definitions/restbuilder.js
RESTBuilder.upgrade(function(builder) {
	builder.header('X-App', 'eshop');
});
```

### RESTBuilder.addTransform(name, fn, [isDefault])

Type: `method`

Registers a function that changes parsed responses.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the transformation. |
| `fn` | `Function` | yes |  | `function(value, output)` returning the new value. |
| `isDefault` | `Boolean` | no | `false` | Use it for all builders. |

Returns: `undefined`

`fn(value, output)` runs with `this` as the builder and returns the new value. A builder uses it after `setTransform(name)`; with `isDefault`, every new builder uses it. `RESTBuilder.setDefaultTransform(name)` changes the default and `RESTBuilder.setDefaultTransform()` removes it. The transformation does not run when the response is a Total.js error array that becomes `err`.

Example: Unwrap a data envelope
```js
RESTBuilder.addTransform('envelope', function(value, output) {
	return value && value.data ? value.data : value;
});

RESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {
	console.log(users);
});
```

### builder.url([url])

Type: `method`

Reads or sets the URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | The address. |

Returns: `RESTBuilder|String` The builder, or the URL when called without an argument.

Without an argument it returns the current URL.

Example: Set the URL
```js
var builder = RESTBuilder.GET('https://api.example.com/');
builder.url('https://api.example.com/v2/products/');
```

### builder.method(method, [data])

Type: `method`

Sets the HTTP method.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `method` | `String` | yes |  | For example `POST` or `put`. |
| `data` | `Object` | no |  | The body, sent as JSON. |

Returns: `RESTBuilder` The builder, for chaining.

Lower-case names are converted to upper case. `data` is sent as JSON.

Example: Choose the method
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/P01/');
	builder.method('PUT', { price: 20 });
	builder.callback(console.log);
});
```

### builder.get([data])

Type: `method`

Switches to `GET` and sets the query string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | Query string arguments. |

Returns: `RESTBuilder` The builder, for chaining.

`data` replaces the query. Alias `builder.GET()`.

Example: Query
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/search/');
	builder.get({ q: 'bike' });
	builder.callback(console.log);
});
```

### builder.post([data])

Type: `method`

Switches to `POST` and sets the body.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object|String` | no |  | The body. |

Returns: `RESTBuilder` The builder, for chaining.

The body keeps the type set earlier (`urlencoded()`, `xml()`), otherwise it is JSON. Alias `builder.POST()`.

Example: POST
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/orders/');
	builder.post({ product: 'P01', count: 1 });
	builder.callback(console.log);
});
```

### builder.put([data])

Type: `method`

Switches to `PUT` and sets the body.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object|String` | no |  | The body. |

Returns: `RESTBuilder` The builder, for chaining.

`builder.patch([data])` and `builder.delete([data])` work the same with `PATCH` and `DELETE`; `builder.head()` switches to `HEAD`. Each has an upper-case alias (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`).

Example: PUT and DELETE
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/P01/');
	builder.put({ price: 20 });
	builder.callback(console.log);
});

RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/P02/');
	builder.delete();
	builder.callback(console.log);
});
```

### builder.header(name, value)

Type: `method`

Sets a request header.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the header. |
| `value` | `String` | yes |  | The value. |

Returns: `RESTBuilder` The builder, for chaining.

For a CSRF token you can also use `builder.csrf(value)` (`X-Csrf-Token`), and `builder.origin(value)` for `Origin`.

Example: Token header
```js
RESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);
```

### builder.type(value)

Type: `method`

Sets the `Content-Type` header.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The content type. |

Returns: `RESTBuilder` The builder, for chaining.

It overrides the type that `json()`, `xml()` and the other body methods set.

Example: Custom type
```js
RESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);
```

### builder.accept(type)

Type: `method`

Sets the `Accept` header.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | An extension or a content type. |

Returns: `RESTBuilder` The builder, for chaining.

A short value is an extension (`json`, `xml`) and is converted to its content type; a longer value is used as it is.

Example: Ask for XML
```js
RESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);
```

### builder.auth(user, [password])

Type: `method`

Sets the `Authorization` header.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `user` | `String` | yes |  | The user name, or the whole header value. |
| `password` | `String` | no |  | The password. |

Returns: `RESTBuilder` The builder, for chaining.

With a password it creates Basic authentication. Without it, `user` is the whole value, for example `Bearer TOKEN`.

Example: Basic and Bearer
```js
RESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);
RESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);
```

### builder.cookie(name, value)

Type: `method`

Adds a cookie to the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name. |
| `value` | `String` | yes |  | The value. |

Returns: `RESTBuilder` The builder, for chaining.

`builder.cookies(obj)` replaces all cookies with an object `{ name: value }`.

Example: Send a session cookie
```js
RESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);
```

### builder.cook([enable])

Type: `method`

Collects the cookies of the responses.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` turns it off. |

Returns: `RESTBuilder` The builder, for chaining.

Cookies set by the server, also during redirects, are stored in the object of `cookies()` and returned by `output.cookie(name)`. Pass the same object to the next builder to keep a session.

Example: Keep a session
```js
var jar = {};
RESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {
	RESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);
});
```

### builder.json([data])

Type: `method`

Sends the body as JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object|String` | no |  | The body. |

Returns: `RESTBuilder` The builder, for chaining.

A `GET` becomes a `POST`.

Example: JSON body
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/');
	builder.json({ name: 'Item' });
	builder.callback(console.log);
});
```

### builder.urlencoded([data])

Type: `method`

Sends the body as `application/x-www-form-urlencoded`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object|String` | no |  | The body. |

Returns: `RESTBuilder` The builder, for chaining.

A `GET` becomes a `POST`. An object is encoded as a form.

Example: Form body
```js
RESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);
```

### builder.xml([data], [replace])

Type: `method`

Sends the body as XML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `String` | no |  | The XML. |
| `replace` | `Boolean` | no | `false` | Passed to `parseXML()` for the response. |

Returns: `RESTBuilder` The builder, for chaining.

Sets `Content-Type: text/xml`; a `GET` becomes a `POST`. Send the XML as a string. An XML response is parsed with `String.parseXML()`; `replace` is its argument.

Example: SOAP-like call
```js
RESTBuilder.make(function(builder) {
	builder.url('https://service.example.com/rates/');
	builder.xml('<request><currency>EUR</currency></request>');
	builder.callback(console.log);
});
```

### builder.plain([value])

Type: `method`

Sends a text body and returns the response as text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | no |  | The body. |

Returns: `RESTBuilder` The builder, for chaining.

Sets `Content-Type: text/plain`. The response is not parsed: `response` is the raw body.

Example: Read text
```js
RESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {
	console.log(text);
});
```

### builder.raw(value, type)

Type: `method`

Sets the body and its type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|String|Buffer` | yes |  | The body. |
| `type` | `String` | yes |  | The type of the body. |

Returns: `RESTBuilder` The builder, for chaining.

`type` is `json`, `urlencoded`, `xml`, `plain`, `html` or `raw` (`application/octet-stream`). An object is serialized when the request is sent, except for type `raw`: send a string or a `Buffer` there.

Example: Binary body
```js
RESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);
```

### builder.set(name, [value])

Type: `method`

Sets one field of the body.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Object` | yes |  | The field, or an object of fields. |
| `value` | `Object` | no |  | The value. |

Returns: `RESTBuilder` The builder, for chaining.

`name` can be an object with several fields. `builder.rem(name)` removes a field. With `file()`, the fields are sent as form fields.

Example: Fields
```js
RESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);
```

### builder.file(name, filename, [source])

Type: `method`

Adds a file to upload.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the form field. |
| `filename` | `String` | yes |  | The file name. |
| `source` | `Buffer|String` | no |  | The content, a path or a URL. |

Returns: `RESTBuilder` The builder, for chaining.

The request becomes `multipart/form-data`, and a `GET` becomes a `POST`. `source` is a `Buffer`, a path or a URL; a URL is downloaded and forwarded. Without `source`, `filename` is read as a path and only its name is sent. The content type comes from the extension of `filename`.

Example: Upload two files
```js
RESTBuilder.POST('https://api.example.com/upload/')
	.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))
	.file('data', 'data.json', Buffer.from(JSON.stringify(data)))
	.callback(console.log);
```

### builder.timeout(ms)

Type: `method`

Sets the timeout.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ms` | `Number` | yes | `10000` | Milliseconds. |

Returns: `RESTBuilder` The builder, for chaining.

The default of a builder is `10000`. After the timeout `err` is the text of status `408`.

Example: Short timeout
```js
RESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);
```

### builder.keepalive()

Type: `method`

Reuses connections.

Returns: `RESTBuilder` The builder, for chaining.

The request uses a shared keep-alive agent. It has no effect with a proxy.

Example: Many calls to one host
```js
RESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);
```

### builder.proxy(url)

Type: `method`

Sends the request through a proxy server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | For example `http://user:password@proxy.example.com:8080`. |

Returns: `RESTBuilder` The builder, for chaining.

The URL can contain credentials. For all requests set `CONF.default_proxy`.

Example: Proxy
```js
RESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);
```

### builder.cert(key, cert, [dhparam])

Type: `method`

Sets a TLS client certificate.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `Buffer` | yes |  | The private key. |
| `cert` | `Buffer` | yes |  | The certificate. |
| `dhparam` | `Buffer` | no |  | Diffie-Hellman parameters. |

Returns: `RESTBuilder` The builder, for chaining.

Use it for services that require client certificates. `builder.insecure()` accepts invalid server certificates (for testing only).

Example: Client certificate
```js
RESTBuilder.GET('https://bank.example.com/api/')
	.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))
	.callback(console.log);
```

### builder.nodnscache()

Type: `method`

Turns off the DNS cache for this request.

Returns: `RESTBuilder` The builder, for chaining.

A builder resolves the host name once and keeps the address; this resolves it as usual. Local addresses are never cached.

Example: Fresh DNS
```js
RESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);
```

### builder.redirect(enable)

Type: `method`

Turns following of redirects on or off.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | yes |  | Follow redirects. |

Returns: `RESTBuilder` The builder, for chaining.

`redirect(false)` returns the `301` or `302` response itself. Redirects are followed by default.

Example: Read the location
```js
RESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) {
	console.log(output.headers.location);
});
```

### builder.unixsocket(socket, path)

Type: `method`

Sends the request to a Unix socket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `socket` | `String` | yes |  | The path of the socket file. |
| `path` | `String` | yes |  | The path of the request. |

Returns: `RESTBuilder` The builder, for chaining.

A URL set earlier becomes the path.

Example: Local service
```js
RESTBuilder.make(function(builder) {
	builder.unixsocket('/var/run/app.sock', '/api/status/');
	builder.callback(console.log);
});
```

### builder.xhr()

Type: `method`

Adds `X-Requested-With: XMLHttpRequest`.

Returns: `RESTBuilder` The builder, for chaining.

Example: XHR
```js
RESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);
```

### builder.referrer(value)

Type: `method`

Sets the `Referer` header.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The URL. |

Returns: `RESTBuilder` The builder, for chaining.

Alias `builder.referer()`.

Example: Referer
```js
RESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);
```

### builder.encrypt([key])

Type: `method`

Encrypts the body and decrypts the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no | `DEF.secret_encryption` | The key. |

Returns: `RESTBuilder` The builder, for chaining.

Uses the framework encryption with `key`, or `DEF.secret_encryption`, and adds `X-Encryption`. Both sides must use the same key.

Example: Encrypted call
```js
RESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);
```

### builder.cache(expire)

Type: `method`

Caches a successful response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `expire` | `String` | yes |  | For example `5 minutes`. |

Returns: `RESTBuilder` The builder, for chaining.

A response with status `200` is stored in `F.cache` for `expire`; the key is made from the URL and the body. `builder.nocache()` skips the cache for one call.

Example: Cache rates
```js
RESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);
```

### builder.schema(name)

Type: `method`

Validates the response with a schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the schema. |

Returns: `RESTBuilder` The builder, for chaining.

The callback gets the model created by the schema. Errors of the schema and a status code `400` or higher come back as `err`. The method throws when the schema does not exist.

Example: Validate the response
```js
NEWSCHEMA('Rate', function(schema) {
	schema.define('currency', 'String(3)', true);
	schema.define('value', Number, true);
});

RESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {
	console.log(err, rate);
});
```

### builder.map(map)

Type: `method`

Keeps and converts selected fields of the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `map` | `String` | yes |  | For example `id:number,name:string,dtcreated:date:created`. |

Returns: `RESTBuilder` The builder, for chaining.

`map` lists `field:type` pairs separated by commas. A third part renames the field: `source:type:target`. It works for an object and for an array of objects.

Example: Map a list
```js
RESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {
	console.log(users);
});
```

### builder.convert(schema)

Type: `method`

Converts fields of the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | For example `price:number,date:date`. |

Returns: `RESTBuilder` The builder, for chaining.

The response goes through `CONVERT(value, schema)`. It does not run together with `schema()`.

Example: Convert types
```js
RESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);
```

### builder.strict()

Type: `method`

Treats status codes `400` and higher as errors.

Returns: `RESTBuilder` The builder, for chaining.

Then `err` is the status code. Without it you must check `output.status` yourself.

Example: Fail on 404
```js
RESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {
	if (err === 404)
		console.log('Not found');
});
```

### builder.noparse()

Type: `method`

Returns the raw body without parsing.

Returns: `RESTBuilder` The builder, for chaining.

`response` is the body as text (or a `Buffer` for binary types).

Example: Raw JSON
```js
RESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {
	Fs.writeFile(PATH.temp('export.json'), body, NOOP);
});
```

### builder.setTransform(name)

Type: `method`

Uses a registered transformation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the transformation. |

Returns: `RESTBuilder` The builder, for chaining.

See `RESTBuilder.addTransform()`.

Example: Use a transformation
```js
RESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);
```

### builder.progress(fn)

Type: `method`

Reports the progress of the download.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(percentage)`. |

Returns: `RESTBuilder` The builder, for chaining.

`fn(percentage)` runs for every chunk. It needs the `Content-Length` header of the response; without it the percentage is `0`.

Example: Progress
```js
RESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {
	console.log(percentage.floor(1) + '%');
}).callback(console.log);
```

### builder.debug()

Type: `method`

Logs the request and the response.

Returns: `RESTBuilder` The builder, for chaining.

Prints the status, method, URL, error and raw body to the console.

Example: Debug
```js
RESTBuilder.GET('https://api.example.com/').debug().callback(console.log);
```

### builder.callback([fn])

Type: `method`

Sends the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|Object` | no |  | `function(err, response, output)`, or `$`. |

Returns: `RESTBuilder|Promise` The builder, or a promise without a function.

With a function, `fn(err, response, output)` runs with the result. Without a function, or with `$` of a schema operation, the method returns a promise: with `$`, an error goes to `$.invalid()`.

Example: Callback
```js
RESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {
	console.log(err, response, output.status);
});
```

Example: Promise
```js
var items = await RESTBuilder.GET('https://api.example.com/items/').callback();
```

### builder.exec([callback])

Type: `method`

Sends the request at once.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `function(err, response, output)`. |

Returns: `RESTBuilder` The builder, for chaining.

`callback(err, response, output)` is the same as in `callback()`; `exec()` sends immediately, `callback()` on the next tick.

Example: Exec
```js
RESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {
	console.log(response);
});
```

### builder.promise([$])

Type: `method`

Sends the request and returns a promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | no |  | The options of an operation. |

Returns: `Promise` A promise of the parsed response.

The promise resolves with the parsed response. With `$` (the options of a schema operation), an error is passed to `$.invalid()` and the promise does not settle; without it the promise rejects.

Example: In an operation
```js
schema.action('sync', {
	name: 'Sync',
	action: async function($) {
		var items = await RESTBuilder.GET('https://api.example.com/items/').promise($);
		$.callback(items);
	}
});
```

### builder.stream(callback)

Type: `method`

Sends the request and returns the response as a stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(err, response)`. |

Returns: `RESTBuilder` The builder, for chaining.

`callback(err, response)` receives `status`, `headers`, `origin` and `stream` (the incoming message). The body is not read or parsed.

Example: Pipe to a file
```js
RESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {
	if (!err)
		response.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));
});
```

### output.cookie(name)

Type: `method`

Reads a cookie from the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the cookie. |

Returns: `String` The value.

`output` is the third argument of the callback. The method reads the `Set-Cookie` headers, or the cookies collected by `cook()`, and returns the decoded value or an empty string.

Example: Read a cookie
```js
RESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {
	var session = output.cookie('session');
});
```
