# Call other servers with REQUEST and save files with DOWNLOAD

> Use REQUEST() for low-level HTTP calls with full control over method, headers, query and body, and DOWNLOAD() to stream a remote file to disk.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 53c1ccdf8b9d50fa08069f0f719cced7ec9528bd28bd251c9307fff966f9aaec
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`REQUEST(options)` is the low-level HTTP client that `RESTBuilder` is built on. Pass an object and `await` it (or give it a callback as the second argument). The useful options are `url`, `method` (default `GET`), `query` (an object, appended to the URL), `headers`, `cookies`, `body` (a string or a Buffer), `type` (`json`, `text`, `html`, `xml`, `urlencoded` or `raw`, which sets `content-type`), `timeout` in milliseconds and `noredirect`.

The result is an object with `status`, `headers`, `cookies` and `body` (a string; parse JSON yourself with `.parseJSON()`). A response with an error status such as 404 is **not** an error: check `status`. The promise only rejects when the request itself fails (connection refused, timeout, invalid host).

`DOWNLOAD(url, filename)` streams the response into a file and resolves with `{ status, size, filename }`. It does not look at the status, so check it before using the file.

```js controllers/request.js
exports.install = function() {
	ROUTE('GET /remote/', remote);
	ROUTE('POST /remote/ @json', remote_post);
	ROUTE('GET /remote/text/', remote_text);
	ROUTE('GET /call/', call);
	ROUTE('GET /download/', download);
};

function remote($) {
	$.json({ hello: 'world', name: $.query.name || null });
}

function remote_post($) {
	$.json({ received: $.body, token: $.headers['x-token'] || null });
}

function remote_text($) {
	$.plain('first line\nsecond line\n');
}

async function call($) {

	var get = await REQUEST({ url: $.hostname('/remote/'), query: { name: 'Louis' } });
	var post = await REQUEST({ method: 'POST', url: $.hostname('/remote/'), type: 'json', body: JSON.stringify({ a: 1 }), headers: { 'x-token': 'abc' } });
	var missing = await REQUEST({ url: $.hostname('/does-not-exist/') });

	var failed = null;
	try {
		await REQUEST({ url: 'http://127.0.0.1:1/' });
	} catch (e) {
		failed = true;
	}

	$.json({
		get: get.body.parseJSON(),
		post: post.body.parseJSON(),
		status: [get.status, missing.status],
		failed: failed
	});
}

async function download($) {
	var filename = PATH.tmp('forge-download.txt');
	var response = await DOWNLOAD($.hostname('/remote/text/'), filename);
	var content = require('fs').readFileSync(filename).toString('utf8');
	$.json({ status: response.status, size: response.size, content: content });
}
```
