---
title: APIs
project: Total.js V5
version: 0.0.20
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/apis/
updated: 2026-11-16T15:32:52.498Z
---

# APIs

> Register named APIs with NEWAPI(), call remote services through them with API(), and use the Total.js API service.

## Registering an API

`NEWAPI()` registers the code that talks to one service. It receives the options of the call and a `next(err, response)` callback; `this` is the API call:

```js
NEWAPI('Weather', function(opt, next) {
	// opt.schema is the operation, opt.data the payload
	var req = {};
	req.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city);
	req.method = 'GET';
	req.type = 'json';
	req.callback = function(err, response) {
		if (err && opt.retries < 3)
			opt.retry();
		else
			next(err, response && response.body.parseJSON());
	};
	REQUEST(req);
});
```

A name is found in the spelling given to `NEWAPI()` or in lower case, and several names separated by commas share one handler. The name `*` registers a handler for every name that has none. A function alone (or a config object and a function) registers the name `default`, and `NEWAPI(name, null)` removes a handler. `opt.retry()` runs the handler again and increases `opt.retries`.

An optional `config` object between the name and the handler holds default settings. They are copied into `opt.config` of every call, unless the call sets the same key with `.configure()`:

```js
NEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) {
	// opt.config.region, opt.config.units
	next(null, { region: opt.config.region });
});

API('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log);
```

## Calling an API

`API(name, schema, data, [$])` runs the handler on the next tick and returns an object whose methods configure the call:

```js
NEWACTION('weather_read', {
	input: '*city:String',
	action: function($, model) {
		API('Weather', 'current', model).error('City not found').callback($);
	}
});

// with a promise
var forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise();
```

| Method | What it does |
| --- | --- |
| `.callback(fn)`, `.pipe(fn)` | Sets `function(err, response)`, or passes the result to `$.callback()` |
| `.promise([$])` | Returns a promise; with `$` an error goes to `$.invalid()` |
| `.data(fn)` / `.fail(fn)` | Runs `fn(response)` on success or `fn(err)` on error |
| `.error(message, [reverse])` | Turns an empty response (or, with `reverse`, any truthy one, an empty array too) into an error |
| `.output(type)` | Sets `opt.output`, the format the handler should return |
| `.file(filename, path, [name])` | Adds a file to `opt.files` |
| `.configure(obj)` | Copies keys into `opt.config` |
| `.controller($)` | Sets `opt.controller` |
| `.audit($, message, [type])` | Writes an audit log with `$.audit()` after a successful call |
| `.debug()` | Prints the error and the response to the console |

A name without a handler (and no `*` handler) fails with `API is not initialized`.

## Total.js API

`TotalAPI(schema, data, [callback])` is a short form of `API('TAPI', schema, data)`. It sends a `POST` request to `https://<$tapiurl>.api.totaljs.com/<schema>/` with your token:

```js
// /config
totalapi       : your-totalapi-token

// code
TotalAPI('check', {}, function(err, response) {
	console.log(err, response);
});

// "operation" is the name of a Total API operation that returns a file
API('TAPI', operation, data).output('#files').callback(console.log);
```

The token is read from `.configure({ token: '...' })`, then `CONF.totalapi`, `CONF.secret_totalapi` or `CONF.$tapisecret`. When `$tapi` is `false`, every operation except `check` fails with `totalapi_inactive`. With `.output()` you choose the format of the response: `json` (default), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, or `#storage [id] [filename]`, which saves the response into a [FileStorage](../../guides/file-storage/) and returns the metadata of the saved file. Error responses (status above `200`) fail with the error message sent by Total API.

For the WebSocket server itself see [WebSockets](../../guides/websockets/), and for outgoing HTTP calls see [HTTP requests](../../guides/http-requests/).
