# Call external services with API() and NEWAPI() drivers

> Register a driver for a service with NEWAPI() and call it from actions with API(name, schema, data), with the same callback, error and promise style as the query builder.

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

`API(name, schema, data, [$])` calls an operation of an external service and `NEWAPI()` registers the **driver** that makes the call, so the code of your actions does not depend on how the service is reached (HTTP, a library, a queue...).

- `NEWAPI('name', driver)` registers the driver of the service `name` (`'a,b'` registers one driver for two names, and `NEWAPI(driver)` registers the `default` one). `NEWAPI('name', config, driver)` also stores a `config` object that every call receives as `options.config`.
- The driver is `function(options, next)`. `options.name` is the service, `options.schema` the operation, `options.data` the data and `options.config` the configuration. Answer with `next(error, response)`.
- `API('name', 'operation', data)` returns a builder: finish it with `.callback($)` (the response goes to the action `$`), `.callback(function(err, response) {})` or `await ....promise($)`. `.configure({ key: value })` adds to `options.config` for that call, and `.error('text')` makes an empty answer fail with that message.
- If no driver is registered for the name the call fails with `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 });
}

```
