---
title: HTTP requests
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/http-requests/
updated: 2026-11-18T16:57:29.576Z
---

# HTTP requests

> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() and Total.download().

The global functions and the `RESTBuilder` class for HTTP requests to other services. For an introduction with examples read the guide [HTTP requests](../../guides/http-requests/). The WebSocket client `OPENCLIENT()` has its own page: [OpenClient](../openclient/).

## API

### REQUEST(options, [callback])

Type: `method`

Sends an HTTP request with full control of the options.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options.url` | `String` | yes |  | The URL of the request. Credentials in the URL (`https://user:password@host/`) are sent as `Authorization: Basic`; percent-encoded characters in them are decoded first. |
| `options.method` | `String` | no | `'GET'` | The HTTP method in upper case. |
| `options.headers` | `Object` | no |  | Request headers. The object is copied, so your object is not changed. |
| `options.type` | `String` | no |  | Sets `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` or `'text'`, `'raw'` (`application/octet-stream`). |
| `options.body` | `String|Buffer` | no |  | The request body. A string is sent as UTF-8; `Content-Length` is set for you. |
| `options.query` | `Object|String` | no |  | Appended to the URL as a query string. |
| `options.cookies` | `Object` | no |  | Cookies to send, as `{ name: value }`. |
| `options.cook` | `Boolean` | no |  | Stores the cookies of the response into `options.cookies`, so the same options object sends them with the next request. |
| `options.timeout` | `Number` | no | `8000` | Timeout in milliseconds; `0` disables it. |
| `options.encoding` | `String` | no | `'utf8'` | Encoding of a text body. `'binary'` returns a `Buffer`. |
| `options.xhr` | `Boolean` | no |  | Adds `X-Requested-With: XMLHttpRequest`. |
| `options.files` | `Array` | no |  | Files for a `multipart/form-data` request: `[{ name, filename, buffer \| path \| url }]`. `options.body` is then an object of extra form fields. |
| `options.compress` | `String` | no |  | Compresses the body: `'gzip'` or `'deflate'`, and sets `Content-Encoding`. |
| `options.encrypt` | `String` | no |  | A key: the body is encrypted with it and the text response is decrypted with it. |
| `options.writer` | `Function` | no |  | `function(req)` writes the body itself: it gets the Node.js request, writes the data and calls `req.end()`. `body` and `files` are then not used. |
| `options.custom` | `Boolean` | no |  | Returns `response.stream` instead of reading the body. |
| `options.noredirect` | `Boolean` | no |  | Does not follow redirects; the callback gets the `301`/`302` response. |
| `options.keepalive` | `Boolean` | no |  | Uses a shared keep-alive agent (one for HTTP, one for HTTPS). |
| `options.resolve` | `Boolean` | no |  | Resolves the hostname with a DNS cache. `options.dnscache` does the same. Skipped for `localhost` and IP addresses. |
| `options.proxy` | `String` | no |  | A proxy for this request, as `'host:port'` or `'http://host:port'`. With `http://user:password@host:port` the credentials are sent as `Proxy-Authorization: Basic`. |
| `options.insecure` | `Boolean` | no |  | Accepts invalid or self-signed TLS certificates. |
| `options.key` | `Buffer` | no |  | Client TLS key. |
| `options.cert` | `Buffer` | no |  | Client TLS certificate. |
| `options.dhparam` | `Buffer` | no |  | TLS Diffie-Hellman parameters. |
| `options.unixsocket` | `Object` | no |  | `{ socket, path }` to send the request through a Unix socket instead of `url`. |
| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` for every received chunk. |
| `options.onprogress` | `Function` | no |  | `function(percentage)`; the percentage is known only with `Content-Length`. |
| `options.callback` | `Function` | no |  | `function(err, response)`, instead of the second argument. |
| `callback` | `Function` | no |  | `function(err, response)`. |

Returns: `Promise` A promise when no callback is given; otherwise nothing.

Sends one HTTP request described by `options`. The callback receives `(err, response)`; without a callback (in the argument or in `options.callback`) it returns a promise that resolves with `response`.

The response object has `status`, `headers`, `body`, `host`, `origin` (the resolved IP addresses when DNS caching is on) and `cookies` (the cookies collected on redirects). `body` is a string for `text/*` and `application/*` types (decoded with `encoding`) and a `Buffer` for the other types, or always a `Buffer` with `encoding: 'binary'`. The body is not parsed: use `RESTBuilder` or `AJAX()` for that.

With `custom: true` the callback runs as soon as the headers arrive and the response has `stream` (the Node.js response) instead of `body`.

Errors: a network error passes the error object with `response.status === 0`; an expired timeout passes `'408: Request Timeout'` with `response.status === 408`; more than four redirects pass `'Too many redirects'`; a URL without a hostname passes `'Invalid hostname'`, and a string that is not a URL throws `TypeError: Invalid URL`. A status code of `400` or more is not an error: check `response.status`.

Redirects `301` and `302` are followed (cookies of the redirect are sent to the next location). Requests use the proxy of the configuration key `$proxyrequest` when it is set, except for `localhost`, `127.0.0.1` and `0.0.0.0`.

Example: POST JSON
```js
REQUEST({
	url: 'https://api.example.com/orders/',
	method: 'POST',
	type: 'json',
	body: JSON.stringify({ id: 'p100', count: 2 })
}, function(err, response) {
	if (err || response.status !== 200)
		return;
	var order = response.body.parseJSON();
});
```

Example: With a promise
```js
var response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });
console.log(response.status, response.body);
```

Example: Upload a file
```js
REQUEST({
	url: 'https://files.example.com/upload/',
	method: 'POST',
	files: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],
	body: { folder: 'reports' }
}, console.log);
```

Example: Read a stream
```js
REQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {
	if (!err)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));
});
```

Example: Write the body yourself
```js
REQUEST({
	url: 'https://api.example.com/import/',
	method: 'POST',
	type: 'plain',
	writer: function(req) {
		for (var line of lines)
			req.write(line + '\n');
		req.end();
	}
}, console.log);
```

### AJAX('METHOD url', [data], [callback])

Type: `method`

Sends a JSON request and returns the parsed response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | `'METHOD url'`, for example `'POST https://example.com/api/'`. |
| `data` | `Object` | no |  | Data sent as JSON. |
| `callback` | `Function` | no |  | `function(err, response, meta)`. |

Returns: `Promise` A promise when no callback is given.

Sends a request and parses the response. The first argument is the method and the URL separated by a space; without a method it is `GET`. `data` is sent as a JSON body. The header `X-Requested-With: XMLHttpRequest` is always added.

The response is parsed by its `Content-Type`: JSON (`application/json`, `text/json`), URL-encoded data and XML (`application/xml`, `text/xml`) become objects; other types are returned as the raw body. An XML document becomes a flat object: the names of nested elements are joined with `_` (`order_name`), repeated elements give an array, and the attributes of an element are in an object under its name with `__` (`order__`). An empty XML body gives `{}`. The callback receives `(err, response, meta)` where `meta` has `status`, `headers` and `host`.

For a status of `400` or more `err` is the parsed body (for a Total.js service the error array) and `response` is `null`. Without a callback the function returns a promise that resolves with the parsed body and rejects with `err`; a Total.js error array becomes an `Error` whose message holds the error messages.

Example: Callback
```js
AJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {
	console.log(meta.status, response);
});
```

Example: Promise
```js
var products = await AJAX('GET https://api.example.com/products/?page=1');
```

Example: XML answer
```js
// the service answers <order id="100"><name>Book</name><items><item>A</item><item>B</item></items></order>
var order = await AJAX('GET https://api.example.com/orders/100/');
// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }
```

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

Type: `method`

Downloads a remote file to the disk.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Object` | yes |  | The URL, or `{ socket, path }` for a Unix socket. |
| `filename` | `String` | yes |  | The target file path. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `timeout` | `Number` | no | `8000` | Timeout in milliseconds. |

Returns: `Promise` A promise when no callback is given.

Downloads `url` and writes the body to `filename`. The callback runs when the file is written, with `(err, response)`. `response` has `status`, `headers`, `origin`, `filename` and `size` (the number of bytes written). The body is saved for every status code, so check `response.status`.

`url` can also be an object `{ socket, path }` for a Unix socket. DNS lookups are cached. `timeout` is in milliseconds (8 seconds when not set). Without a callback the function returns a promise that resolves with `response`.

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

Example: Promise
```js
var response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));
```

### Total.download(url, filename, [callback], [timeout])

Type: `method`

The framework method behind DOWNLOAD().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Object` | yes |  | The URL, or `{ socket, path }` for a Unix socket. |
| `filename` | `String` | yes |  | The target file path. |
| `callback` | `Function` | no |  | `function(err, response)`. |
| `timeout` | `Number` | no | `8000` | Timeout in milliseconds. |

Returns: `Promise` A promise when no callback is given.

The same function as `DOWNLOAD()`. Downloads `url` and writes the body to `filename`. The callback runs when the file is written, with `(err, response)`. `response` has `status`, `headers`, `origin`, `filename` and `size` (the number of bytes written). The body is saved for every status code, so check `response.status`.

`url` can also be an object `{ socket, path }` for a Unix socket. DNS lookups are cached. `timeout` is in milliseconds (8 seconds when not set). Without a callback the function returns a promise that resolves with `response`.

Example: Download
```js
Total.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {
	console.log(err, response.status);
});
```

### new RESTBuilder([url])

Type: `class`

A builder for requests to REST services.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | The URL of the request. |

Returns: `RESTBuilder` A new builder.

A global class. A new builder has the method `GET`, a timeout of 10 seconds, DNS caching on, the header `user-agent: Total.js/v...` and `accept: application/json, text/plain, text/plain, text/xml`. Nothing is sent until you call `callback()`, `promise()`, `stream()` or `exec()`.

You usually start with a static helper: `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` or `make()`. `RESTBuilder.url(url)` is the same as `new RESTBuilder(url)`.

Example: Create a builder
```js
var builder = RESTBuilder.url('https://api.example.com/users/');
builder.header('X-Token', CONF.apitoken);
builder.callback(console.log);
```

### RESTBuilder.make(fn)

Type: `method`

Creates a builder and passes it to a function.

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

Returns: `RESTBuilder` The new builder.

Creates a builder without a URL and calls `fn(builder)`. Set the URL with `builder.url()`. The instance method `builder.make(fn)` calls `fn` with the builder as `this` and as the argument, for reusable settings.

Example: Build a request
```js
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/users/');
	builder.post({ name: 'Peter' });
	builder.callback(console.log);
});
```

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

Type: `method`

Creates a GET request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL. |
| `data` | `Object` | no |  | Sent as the query string. |

Returns: `RESTBuilder` A new builder.

Creates a builder with the method `GET`; `data` becomes the query string. For a `HEAD` request use `RESTBuilder.HEAD(url)`: it has no data, the parsed value is an empty object and you read `output.status` and `output.headers`.

Example: Query string
```js
RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {
	console.log(response);
});
```

Example: HEAD
```js
RESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {
	console.log(output.status, output.headers['last-modified']);
});
```

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

Type: `method`

Creates a POST request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL. |
| `data` | `Object` | no |  | Sent as a JSON body. |

Returns: `RESTBuilder` A new builder.

Creates a builder with the method `POST`; `data` is sent as JSON. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` and `RESTBuilder.DELETE()` work the same way with their methods.

Example: POST JSON
```js
RESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {
	console.log(order.id);
});
```

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

Type: `method`

Creates a PUT request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL. |
| `data` | `Object` | no |  | Sent as a JSON body. |

Returns: `RESTBuilder` A new builder.

Creates a builder with the method `PUT`; `data` is sent as JSON.

Example: PUT
```js
RESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
```

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

Type: `method`

Creates a PATCH request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL. |
| `data` | `Object` | no |  | Sent as a JSON body. |

Returns: `RESTBuilder` A new builder.

Creates a builder with the method `PATCH`; `data` is sent as JSON.

Example: PATCH
```js
RESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
```

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

Type: `method`

Creates a DELETE request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL. |
| `data` | `Object` | no |  | Sent as a JSON body. |

Returns: `RESTBuilder` A new builder.

Creates a builder with the method `DELETE`; `data` is sent as JSON.

Example: DELETE
```js
RESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);
```

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

Type: `method`

Calls an API endpoint of a Total.js application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL of the API endpoint. |
| `name` | `String` | yes |  | The name of the API operation. |
| `data` | `Object` | no |  | The data of the operation. |

Returns: `RESTBuilder` A new builder.

Creates a `POST` request for a Total.js API route (`ROUTE('API /api/ ...')`). The body is JSON: `{ schema: name, data: data }`. `name` is the API name with optional parameters, for example `'products_detail/p100'`. `builder.get(query)` keeps the `POST` and sends the query in the body as `query`, next to `data`. `builder.compress()` leaves out the keys of the body whose value is `null` or `undefined`.

Example: Call an API
```js
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {
	console.log(err, response);
});
```

Example: With a query
```js
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);
// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }
```

### builder.compress([value])

Type: `method`

Leaves out empty values from the body of a RESTBuilder.API() request.

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

Returns: `RESTBuilder` The same builder, for chaining.

Without an argument or with `true`, the JSON body of a `RESTBuilder.API()` request is written without the keys whose value is `null` or `undefined`, so the request is smaller. `compress(false)` turns it off. Other builders are not affected.

Example: Smaller body
```js
RESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);
// data: { id: 'A1', total: 120 }
```

### RESTBuilder.upgrade(fn)

Type: `method`

Registers a function that changes every builder before it is sent.

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

The function runs for every builder in the application just before the request is made, with the builder as the argument. Use it for shared headers or tokens. Upgrades cannot be removed.

Example: Add a token to one service
```js
RESTBuilder.upgrade(function(builder) {
	if (builder.url().startsWith(CONF.shopapi))
		builder.header('X-Token', CONF.shoptoken);
});
```

### builder.url([url])

Type: `method`

Sets or reads the URL.

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

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

With an argument sets the URL and returns the builder; without one returns the current URL.

Example: Read the URL
```js
var url = builder.url();
```

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

Type: `method`

Sets the HTTP method.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `method` | `String` | yes |  | The HTTP method. |
| `data` | `Object` | no |  | Data sent as JSON. |

Returns: `RESTBuilder` The same builder, for chaining.

Sets the method (lower case is converted to upper case). `data` is sent as JSON.

Shortcuts: `builder.get([query])` sets `GET` and the query string; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` and `builder.delete([data])` set the method and the body (in the type set before, JSON by default); `builder.head()` sets `HEAD`. Upper-case names (`builder.POST()`) are aliases.

Example: Shortcuts
```js
RESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);
```

### builder.json([data])

Type: `method`

Sends data as JSON.

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

Returns: `RESTBuilder` The same builder, for chaining.

Sets the type to JSON and the body to `data` (an object is serialized when the request is sent). A `GET` request becomes `POST`.

Example: JSON body
```js
RESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);
```

### builder.urlencoded([data])

Type: `method`

Sends data as a URL-encoded form.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | The form fields. |

Returns: `RESTBuilder` The same builder, for chaining.

Sets `Content-Type: application/x-www-form-urlencoded` and the body; an object is encoded when the request is sent. A `GET` request becomes `POST`.

Example: Form
```js
RESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);
```

### builder.xml([data])

Type: `method`

Sends an XML body.

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

Returns: `RESTBuilder` The same builder, for chaining.

Sets `Content-Type: text/xml` and the body. Pass the XML as a string. A `GET` request becomes `POST`.

Example: XML body
```js
RESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);
```

### builder.raw(value, [type])

Type: `method`

Sets the body as it is.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Buffer` | yes |  | The body. |
| `type` | `String` | no |  | The short content type. |

Returns: `RESTBuilder` The same builder, for chaining.

Sets the body without any serialization. `type` is one of the short types of `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`); without it set the header with `builder.type()`. A string is sent unchanged. A `Buffer` needs the type `'raw'` (`application/octet-stream`); without a type it is serialized as JSON like an object.

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

### builder.text(value)

Type: `method`

Sends plain text and keeps the response unparsed.

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

Returns: `RESTBuilder` The same builder, for chaining.

`builder.plain(value)` is an alias. Sets `Content-Type: text/plain` and the body, and the callback receives the raw response body instead of a parsed value.

Example: Plain text
```js
RESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {
	// response is the raw body
});
```

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

Type: `method`

Adds a file and sends a multipart request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The form field name. |
| `filename` | `String` | yes |  | The file name sent to the service. |
| `source` | `Buffer|String` | no |  | A buffer, a path or a URL. |

Returns: `RESTBuilder` The same builder, for chaining.

The request becomes `multipart/form-data` (a `GET` becomes `POST`). `source` is a `Buffer`, a path on the disk, or a URL that is downloaded and streamed. Without `source` the file is read from `filename`. The body set with `json()` or `urlencoded()` is sent as extra form fields when it is an object.

Example: Upload two files
```js
RESTBuilder.POST('https://files.example.com/upload/')
	.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))
	.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')
	.callback(console.log);
```

### builder.header(name, value)

Type: `method`

Sets a request header.

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

Returns: `RESTBuilder` The same builder, for chaining.

Sets one header. Helpers for common headers: `builder.referrer(url)` (alias `referer()`) sets `Referer`, `builder.origin(url)` sets `Origin`, `builder.csrf(token)` sets `X-Csrf-Token` and `builder.xhr()` adds `X-Requested-With: XMLHttpRequest`.

Example: Headers
```js
builder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();
```

### builder.type(value)

Type: `method`

Sets the Content-Type header.

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

Returns: `RESTBuilder` The same builder, for chaining.

Sets `Content-Type` to a full MIME type. A type set by `json()`, `urlencoded()`, `xml()` or `text()` replaces it, so use it with `raw(value)`.

Example: Custom type
```js
builder.raw('{"id":1}').type('application/vnd.api+json');
```

### builder.accept(ext)

Type: `method`

Sets the Accept header.

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

Returns: `RESTBuilder` The same builder, for chaining.

Takes a file extension (`'json'`, `'xml'`, `'html'`...) and converts it to its MIME type; a longer value is used as it is.

Example: Accept XML
```js
builder.accept('xml');
```

### 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 same builder, for chaining.

With `user` and `password` sets basic authentication (`Basic base64(user:password)`). With one argument the value is used as it is, for example `'Bearer TOKEN'`.

Example: Basic and Bearer
```js
builder.auth('admin', 'secret');
builder.auth('Bearer ' + CONF.apitoken);
```

### builder.cookie(name, value)

Type: `method`

Adds a cookie to the request.

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

Returns: `RESTBuilder` The same builder, for chaining.

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

Example: Cookies
```js
builder.cookie('session', token);
builder.cookies({ lang: 'en', theme: 'dark' });
```

### builder.cook([value])

Type: `method`

Keeps the response cookies in the builder.

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

Returns: `RESTBuilder` The same builder, for chaining.

With `cook()` the cookies set by the response are stored in the builder and sent with the next request made by the same builder. `output.cookies` then holds them. `cook(false)` turns it off.

Example: Login, then read
```js
RESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {
	RESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);
});
```

### builder.timeout(ms)

Type: `method`

Sets the timeout.

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

Returns: `RESTBuilder` The same builder, for chaining.

The timeout in milliseconds (10000 by default). `0` disables it. When it expires the error is `408: Request Timeout`.

Example: Five seconds
```js
builder.timeout(5000);
```

### builder.keepalive([val])

Type: `method`

Reuses connections with a keep-alive agent.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `val` | `Boolean` | no | `true` | Turns keep-alive on or off. |

Returns: `RESTBuilder` The same builder, for chaining.

Without an argument (or with a truthy value) the request uses the shared keep-alive agent of the framework, so connections to the same host are reused. `keepalive(false)` turns it off. Not used together with a proxy.

Example: Keep-alive
```js
RESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);
```

### builder.proxy(url)

Type: `method`

Sends the request through a proxy.

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

Returns: `RESTBuilder` The same builder, for chaining.

`url` is `'host:port'` or `'http://host:port'`. With `http://user:password@host:port` the credentials are sent as `Proxy-Authorization: Basic`. HTTPS targets are tunneled with `CONNECT`. Without it the proxy of the configuration key `$proxyrequest` is used when set.

Example: Proxy
```js
builder.proxy('http://10.0.0.5:3128');
```

Example: Proxy with a login
```js
builder.proxy('http://user:secret@10.0.0.5:3128');
```

### builder.insecure()

Type: `method`

Accepts invalid TLS certificates.

Returns: `RESTBuilder` The same builder, for chaining.

Accepts self-signed or expired certificates of the service. Use it only for internal services.

Example: Self-signed
```js
RESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);
```

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

Type: `method`

Sets a client TLS 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 same builder, for chaining.

For services that require client certificates.

Example: Client certificate
```js
builder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));
```

### builder.unixsocket(socket, path)

Type: `method`

Sends the request through a Unix socket.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `socket` | `String` | yes |  | The socket file. |
| `path` | `String` | yes |  | The request path, for example `/api/`. |

Returns: `RESTBuilder` The same builder, for chaining.

Connects to the socket file instead of a host; `path` is the URL path of the request.

Example: Docker API
```js
RESTBuilder.make(function(builder) {
	builder.unixsocket('/var/run/docker.sock', '/containers/json');
	builder.callback(console.log);
});
```

### builder.nodnscache()

Type: `method`

Turns off the DNS cache for this request.

Returns: `RESTBuilder` The same builder, for chaining.

By default the builder resolves the hostname once and caches its addresses. With `nodnscache()` Node.js resolves it for every request.

Example: No DNS cache
```js
builder.nodnscache();
```

### builder.redirect(value)

Type: `method`

Turns following redirects on or off.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean` | yes |  | `false` stops following redirects. |

Returns: `RESTBuilder` The same builder, for chaining.

`redirect(false)` returns the `301` or `302` response itself; read the target in `output.headers.location`. By default up to four redirects are followed.

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

### builder.encrypt(key)

Type: `method`

Encrypts the body and decrypts the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The encryption key. |

Returns: `RESTBuilder` The same builder, for chaining.

The body is encrypted with `key` and sent with the header `X-Encryption: a`; a text response is decrypted with the same key. Both sides must use the same key.

Example: Encrypted call
```js
builder.encrypt(CONF.sharedkey);
```

### builder.progress(fn)

Type: `method`

Reports the download progress.

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

Returns: `RESTBuilder` The same builder, for chaining.

Calls `fn(percentage)` for every received chunk. The percentage is known only when the response has `Content-Length`, otherwise it is `0`.

Example: Progress
```js
builder.progress(function(percentage) {
	console.log(percentage.toFixed(1) + '%');
});
```

### builder.noparse()

Type: `method`

Returns the raw response body.

Returns: `RESTBuilder` The same builder, for chaining.

The callback receives the body as a string (or a `Buffer` for binary types) instead of a parsed value.

Example: Raw HTML
```js
RESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {
	console.log(html.length);
});
```

### builder.base64()

Type: `method`

Returns the response body as base64.

Returns: `RESTBuilder` The same builder, for chaining.

The callback receives the body encoded in base64, for example to embed an image as a data URI.

Example: Data URI
```js
RESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {
	var uri = 'data:image/png;base64,' + data;
});
```

### builder.debug()

Type: `method`

Prints the request and the response to the console.

Returns: `RESTBuilder` The same builder, for chaining.

After the response arrives prints the status, the method, the URL with the query, the error and the raw body.

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

### builder.callback([fn])

Type: `method`

Sends the request and receives the parsed response.

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

Returns: `RESTBuilder|Promise` The builder, or a promise when called without an argument.

Sends the request on the next tick and passes the result to `fn(err, response, output)`:

- `response`: the body parsed by its `Content-Type` (JSON, also for `text/plain`; URL-encoded; XML through the HTML parser; other bodies are parsed as JSON when they look like JSON). An empty body gives an empty object; a `204` response gives `true`.
- `output`: `status`, `headers`, `response` (the raw body), `hostname`, `origin`, `cookies` (with `cook()`) and `output.cookie(name)`, which reads a cookie of the response.
- `err`: the network error or `'408: Request Timeout'`; an `ErrorBuilder` when the body is a Total.js error array (`[{ error: '...' }]`, `response` is then `null`); otherwise, for a status of `400` or more, an `ErrorBuilder` with one error whose name is the status code and whose message is the raw body. A value set with `builder.error()` replaces any error.

`fn` can also be the `$` of an action: the parsed response is passed to `$.callback()` and an error is added to the errors of `$`. Without an argument it returns a promise that resolves with `response` and rejects with `err`.

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

Example: In an action
```js
NEWACTION('Products/sync', {
	name: 'Sync products',
	action: function($) {
		RESTBuilder.GET(CONF.shopapi + '/products/').callback($);
	}
});
```

### builder.promise([$])

Type: `method`

Sends the request and returns a promise.

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

Returns: `Promise` Resolves with the parsed response.

The promise resolves with the parsed response. On an error it rejects with an `Error` made from the error (an `ErrorBuilder` becomes an `Error` with its messages). With `$` the error goes to `$.invalid()` instead and the promise is not rejected.

Example: await
```js
var user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();
```

Example: With $
```js
var order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);
```

### 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 same builder, for chaining.

Sends the request immediately and calls `callback(err, response, output)` with the same values as `callback()`. Prefer `callback()`, which waits for the next tick. When `callback` is omitted the result is ignored.

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

### builder.stream(callback)

Type: `method`

Returns the response as a stream.

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

Returns: `RESTBuilder` The same builder, for chaining.

Sends the request on the next tick and calls `callback(err, response)` as soon as the headers arrive. `response` has `status`, `headers`, `origin` and `stream` (the Node.js response, not read yet). Use it for large files.

Example: Save a large file
```js
RESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {
	if (!err && response.status === 200)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));
});
```

### builder.error(value)

Type: `method` · Since: `0.0.16`

Replaces any error with your own value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|String` | yes |  | The error to return, for example a message or an `ErrorBuilder`. |

Returns: `RESTBuilder` The same builder, for chaining.

When the request ends with any error (network, timeout or a status of `400` or more), the callback or the promise receives `value` instead. Use it to hide the details of a remote service from your users.

Example: Own error
```js
RESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);
```

### builder.logerror()

Type: `method` · Since: `0.0.16`

Prints errors to the console.

Returns: `RESTBuilder` The same builder, for chaining.

When the request ends with an error, the error (or the raw response body) is passed to the framework error handler, which prints it with the name `RESTBuilder` and the method and URL of the request. The callback still receives the error.

Example: Log errors
```js
RESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);
```
