# Llama a servicios externos con API() y los drivers de NEWAPI()

> Registra un driver para un servicio con NEWAPI() y llámalo desde las acciones con API(name, schema, data), con el mismo estilo de callback, error y promesa que el query builder.

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

`API(name, schema, data, [$])` llama a una operación de un servicio externo y `NEWAPI()` registra el **driver** que hace la llamada, de modo que el código de tus acciones no depende de cómo se llega al servicio (HTTP, una librería, una cola...).

- `NEWAPI('name', driver)` registra el driver del servicio `name` (`'a,b'` registra un driver para dos nombres y `NEWAPI(driver)` registra el `default`). `NEWAPI('name', config, driver)` guarda además un objeto `config` que cada llamada recibe como `options.config`.
- El driver es `function(options, next)`. `options.name` es el servicio, `options.schema` la operación, `options.data` los datos y `options.config` la configuración. Responde con `next(error, response)`.
- `API('name', 'operation', data)` devuelve un builder: termínalo con `.callback($)` (la respuesta va a la acción `$`), `.callback(function(err, response) {})` o `await ....promise($)`. `.configure({ key: value })` añade a `options.config` para esa llamada y `.error('text')` hace que una respuesta vacía falle con ese mensaje.
- Si no hay ningún driver registrado para el nombre, la llamada falla con `API is not initialized`.

```js definitions/api.js
// The driver of a fake weather service: in a real one this would be an HTTP request
NEWAPI('weather', { unit: 'C' }, function(options, next) {
	if (options.schema === 'forecast')
		next(null, { city: options.data.city, temperature: 21, unit: options.config.unit, service: options.name });
	else
		next('Unknown operation ' + options.schema);
});
```

```js controllers/weather.js
exports.install = function() {
	ROUTE('GET /forecast/', forecast);
	ROUTE('GET /forecast-fahrenheit/', fahrenheit);
	ROUTE('GET /unknown/', unknown);
	ROUTE('GET /missing/', missing);
	ROUTE('GET /promise/', promise);
};

function forecast($) {
	API('weather', 'forecast', { city: $.query.city }).callback($);
}

function fahrenheit($) {
	API('weather', 'forecast', { city: $.query.city }).configure({ unit: 'F' }).callback($);
}

function unknown($) {
	API('weather', 'rain', {}).callback($);
}

function missing($) {
	API('nobody', 'forecast', {}).callback($);
}

async function promise($) {
	const data = await API('weather', 'forecast', { city: 'Oslo' }).promise($);
	$.json({ city: data.city, same: true });
}

```
