# Call other HTTP APIs with RESTBuilder

> Make GET and POST requests to another service, set headers and a timeout, and read the status and the parsed response.

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

`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`).

- `response` is the body, parsed automatically when it is JSON
- `output.status` is the HTTP status and `output.headers` the response headers
- `err` is 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.

```js controllers/service.js
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 });
	});
}
```
