# Call Total.js API routes with API()

> Use API(url, name, data, callback) to call the actions of a ROUTE('API ...') endpoint, validation errors included.

Framework: jcomponent20
Product: jComponent 20 (jcomponent@20)
Language: en
Content-SHA256: 7d1c02bbcfea4e2f336b0f7c326061679b2258d315e46891c6b4e67046dc2b94
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: jcomponent20@3fedd009a277f50fddc608b97afbec553b67c51b
Review: not-recorded

`API(url, name, data, callback)` is the client side of the Total.js `ROUTE('API ...')` endpoints. It sends `POST url` with the body `{ schema: name, data: data }` and calls the callback with the response. When the server answers with an error (for example a validation error) the callback receives an array of errors: use the `ERROR(response, success, error)` helper to handle both cases in one place.

Put the address of the endpoint in `ENV()` once and reuse it.

```js definitions/math.js
NEWACTION('Math/add', {
	name: 'Add two numbers',
	input: '*a:Number, *b:Number',
	action: function($, model) {
		$.callback({ sum: model.a + model.b });
	}
});
```

```js controllers/api.js
exports.install = function() {
	ROUTE('API /api/ +math_add --> Math/add');
};
```

```html public/index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>jComponent</title>
	<link rel="stylesheet" href="//cdn.componentator.com/spa.min@20.css" />
	<script src="//cdn.componentator.com/spa.min@20.js"></script>
</head>
<body>
	<p class="sum"></p>
	<p class="error"></p>

	<script>

		ENV('api', '/api/');

		API('[api]', 'math_add', { a: 20, b: 22 }, function(response) {
			SET('sum', response.sum);
		});

		API('/api/', 'math_add', { a: 'x' }, function(response) {
			ERROR(response, function(value) {
				SET('failed', 'unexpected success');
			}, function(errors) {
				SET('failed', errors[0].name);
			});
		});

	</script>

</body>
</html>
```
