# Llama a otras APIs HTTP con RESTBuilder

> Haz peticiones GET y POST a otro servicio, define cabeceras y un timeout, y lee el estado y la respuesta ya interpretada.

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

`RESTBuilder.GET(url)`, `.POST(url, data)`, `.PUT`, `.PATCH` y `.DELETE` construyen una petición. Los datos de un POST se envían como JSON. Encadena `.header(name, value)`, `.cookie(name, value)`, `.timeout(milliseconds)` y `.auth(user, password)` antes de `.exec(function(err, response, output) {})` (o `.promise()` para `await`).

- `response` es el body, interpretado automáticamente cuando es JSON
- `output.status` es el estado HTTP y `output.headers` las cabeceras de la respuesta
- `err` se rellena en errores de red y en estados HTTP de error

El ejemplo llama a dos rutas de su propia app para poder ejecutarse en cualquier sitio; en tu código usa la dirección del servicio real. `$.hostname(path)` construye la URL completa de este servidor.

```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 });
	});
}
```
