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

# API

> Registra API con nome con NEWAPI(), chiama servizi remoti tramite esse con API() e usa il servizio Total.js API.

## Registrare un'API

`NEWAPI()` registra il codice che comunica con un servizio. Riceve le opzioni della chiamata e una callback `next(err, response)`; `this` è la chiamata API:

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

Un nome viene trovato nella grafia data a `NEWAPI()` o in minuscolo, e più nomi separati da virgole condividono un unico handler. Il nome `*` registra un handler per ogni nome che non ne ha uno. Una funzione da sola (o un oggetto di configurazione e una funzione) registra il nome `default`, e `NEWAPI(name, null)` rimuove un handler. `opt.retry()` esegue di nuovo l'handler e incrementa `opt.retries`.

Un oggetto `config` facoltativo tra il nome e l'handler contiene le impostazioni predefinite. Vengono copiate in `opt.config` di ogni chiamata, a meno che la chiamata non imposti la stessa chiave con `.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);
```

## Chiamare un'API

`API(name, schema, data, [$])` esegue l'handler al tick successivo e restituisce un oggetto i cui metodi configurano la chiamata:

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

| Metodo | Cosa fa |
| --- | --- |
| `.callback(fn)`, `.pipe(fn)` | Imposta `function(err, response)`, oppure passa il risultato a `$.callback()` |
| `.promise([$])` | Restituisce una promise; con `$` un errore va a `$.invalid()` |
| `.data(fn)` / `.fail(fn)` | Esegue `fn(response)` in caso di successo o `fn(err)` in caso di errore |
| `.error(message, [reverse])` | Trasforma una risposta vuota (o, con `reverse`, qualsiasi risposta truthy, anche un array vuoto) in un errore |
| `.output(type)` | Imposta `opt.output`, il formato che l'handler deve restituire |
| `.file(filename, path, [name])` | Aggiunge un file a `opt.files` |
| `.configure(obj)` | Copia chiavi in `opt.config` |
| `.controller($)` | Imposta `opt.controller` |
| `.audit($, message, [type])` | Scrive un log di audit con `$.audit()` dopo una chiamata riuscita |
| `.debug()` | Stampa l'errore e la risposta nella console |

Un nome senza handler (e senza handler `*`) fallisce con `API is not initialized`.

## Total.js API

`TotalAPI(schema, data, [callback])` è una forma breve di `API('TAPI', schema, data)`. Invia una richiesta `POST` a `https://<$tapiurl>.api.totaljs.com/<schema>/` con il tuo 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);
```

Il token viene letto da `.configure({ token: '...' })`, poi da `CONF.totalapi`, `CONF.secret_totalapi` o `CONF.$tapisecret`. Quando `$tapi` è `false`, ogni operazione tranne `check` fallisce con `totalapi_inactive`. Con `.output()` scegli il formato della risposta: `json` (predefinito), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, oppure `#storage [id] [filename]`, che salva la risposta in un [FileStorage](../../guides/file-storage/) e restituisce i metadati del file salvato. Le risposte di errore (stato sopra `200`) falliscono con il messaggio di errore inviato da Total API.

Per il server WebSocket vedi [WebSocket](../../guides/websockets/), e per le chiamate HTTP in uscita vedi [Richieste HTTP](../../guides/http-requests/).
