# Chiamare altre API HTTP con RESTBuilder

> Esegui richieste GET e POST a un altro servizio, imposta header e timeout e leggi lo stato e la risposta interpretata.

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

`RESTBuilder.GET(url)`, `.POST(url, data)`, `.PUT`, `.PATCH` e `.DELETE` costruiscono una richiesta. I dati di un POST vengono inviati come JSON. Concatena `.header(name, value)`, `.cookie(name, value)`, `.timeout(milliseconds)` e `.auth(user, password)` prima di `.exec(function(err, response, output) {})` (o `.promise()` per `await`).

- `response` è il body, interpretato automaticamente quando è JSON
- `output.status` è lo stato HTTP e `output.headers` gli header della risposta
- `err` è valorizzato per errori di rete e per stati HTTP di errore

L'esempio chiama due route della propria app per poter girare ovunque; nel tuo codice usa l'indirizzo del servizio reale. `$.hostname(path)` costruisce l'URL completo di questo 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 });
	});
}
```
