JSON endpoints
A user module of your app answers JSON requests (AJAX calls of your pages, a mobile app, another server) through a method whose
name starts with _api_. There is nothing to register: the method _api_<action>() of the user module
<module> answers /api/<module>/<action>. This page shows how to write one: the URL, the input,
the JSON answer, errors, the CSRF token of a POST, and the docblock tags that describe it.
The URL
/api/<module>/<action>with URL rewriting (pretty URLs), for example/api/notes/hello?name=Ann;/?object=api&action=<module>&id=<action>without it, the same handler.
The handler is a public method of the user module, named _api_ plus the action: /api/notes/hello runs
notes::_api_hello(). A module of your app overrides a framework one as usual, so a site can add or change endpoints the
same way it changes pages. No page, layout or block is rendered around the answer.
Example
A module with two endpoints: a GET that reads, and a POST that changes something for the logged-in user.
<?php
// modules/notes.class.php (your app's user modules folder)
class notes
{
/**
* Greets a visitor.
*
* Answers the name back; nothing is stored.
* @api-method get
* @api-query name string Who to greet
* @api-response 200 object {"text": "Hello, Ann"}
* @api-tag Notes
*/
public function _api_hello()
{
$name = trim((string) ($_GET['name'] ?? ''));
return ['text' => 'Hello, ' . ($name !== '' ? $name : 'world')];
}
/**
* Keeps a note of the logged-in user.
*
* @api-method post
* @api-body object {"text": "the note, 1 to 500 characters"}
* @api-response 200 object {"ok": true, "length": 7}
* @api-response 400 object {"error": "text: 1 to 500 characters"}
* @api-response 403 Not logged in, or no valid token
* @api-tag Notes
*/
public function _api_add($request)
{
$api = _class('api');
if ( ! $api->is_post || ! main()->USER_ID || ! _class('csrf_guard')->check()) {
$api->_forbidden(); // 403, ends the request
}
$text = trim((string) ($request['text'] ?? ''));
if ($text === '' || mb_strlen($text) > 500) {
return [json_encode(['error' => 'text: 1 to 500 characters']), 400, 'json', 'is_raw' => true];
}
db()->insert_safe('notes', ['user_id' => (int) main()->USER_ID, 'text' => $text, 'add_date' => time()]);
return ['ok' => true, 'length' => mb_strlen($text)];
}
}
Its page passes the session's CSRF token to the template, and the page's JavaScript calls the endpoints:
// in the module that renders the page
$replace['csrf_token'] = _class('csrf_guard')->session_token();
<meta name="csrf-token" content="{csrf_token}">
// the answer of a JSON handler starts with the line )]}', : strip it before JSON.parse()
async function yfApi(path, body) {
const opts = { headers: { Accept: 'application/json' } };
if (body !== undefined) {
opts.method = 'POST';
opts.headers['Content-Type'] = 'application/json';
opts.headers['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').content;
opts.body = JSON.stringify(body);
}
const res = await fetch(path, opts);
const text = (await res.text()).replace(/^\)\]\}',\n/, '');
return { status: res.status, data: text.startsWith('{') || text.startsWith('[') ? JSON.parse(text) : text };
}
yfApi('/api/notes/hello?name=Ann'); // {status: 200, data: {text: "Hello, Ann"}}
yfApi('/api/notes/add', { text: 'My note' }); // {status: 200, data: {ok: true, length: 7}}
Input
- Query string:
$_GET, as on any page.$_GET['object'],['action']and['id']are taken by the routing (api, the module, the action),callbackasks for JSONP (below) andlanguage_idsets the language of the request: pick other names for your own parameters. - A JSON body (POST, PUT, PATCH with
Content-Type: application/json) arrives decoded as the first argument of the handler, an array (nullwhen the body is not JSON). A classic form POST is in$_POST. _class('api')tells the request apart:is_get,is_post,is_put,is_patch,is_delete(true or null),request_method. The handler is called for every method: check it yourself when only one makes sense, as_api_add()does.- The logged-in user is
main()->USER_ID(0 for a guest), as on pages: the request carries the session cookie. - Input is untrusted: cast and escape it as everywhere else (
(int),_es(), the*_safe()database methods; the query builder does not escape values).
Output
- Return an array (or any value
json_encode()takes): it is sent as JSON with200 OKandContent-Type: application/json; charset=utf-8. - The JSON is preceded by the line
)]}',and a newline, which keeps an old browser from running the answer as a script on another site. Your JavaScript strips it beforeJSON.parse()(theyfApi()helper above; AngularJS's$httpdoes it by itself). - A GET with
?callback=<name>is answered as JSONP,/**/ name(<json>);, which any other site may load in a<script>tag with the visitor's cookies. So a GET handler returns public data only; what belongs to the logged-in user goes through a POST with the token. - Your own status, body or type: return
[$body, $code, $type, 'is_raw' => true];$typeisjson,javascript,plainorhtml. The body is sent as it is (no)]}',line), sojson_encode()it yourself, as the 400 answer of the example. - Every answer carries
X-Robots-Tag: none, so search engines do not index it.
Errors
/api/<module>/<action>without such a handler answers503 Service Unavailable.- From a handler,
_class('api')->_forbidden()answers403 Forbidden,_error()500and_reject($code)another status, each with the status text as plain body; they end the request. - An error the client should read (a validation message): a raw answer with a JSON body and a 4xx status, as
[json_encode(['error' => '...']), 400, 'json', 'is_raw' => true]. - Do not echo PHP errors or exception texts to the client; log them and answer
_error().
CSRF: a POST carries the token
A handler that changes something (store, delete, send, pay) runs only for a POST (or PUT, PATCH, DELETE) that carries the session's CSRF token, else another site could make a logged-in visitor's browser call it. The dispatcher does not check user-side POSTs for you:
- the page gets the token from
_class('csrf_guard')->session_token()(a<meta>tag, a data attribute or a hidden_tokenfield); - the request sends it in the
X-CSRF-Tokenheader (a JSON body) or as the POST field_token(a form); - the handler checks
_class('csrf_guard')->check(), which compares both withhash_equals(), and refuses with_forbidden(); - a GET never changes anything; a GET handler needs no token.
An endpoint for another server (a webhook, a payment notification) has no session and no token: it checks the caller another way,
for example a signature of the body with a shared secret (hash_hmac() and hash_equals()).
Describing the endpoint (@api-* tags)
The docblock of the handler documents it for the OpenAPI 3.1 document of the site, which the admin panel builds from these tags without running the code. The first paragraph is the summary, the rest before the tags the description, then:
@api-method get post: the HTTP methods (defaultget post);@api-query <name> [<type>] [required] <description>: a query parameter;@api-body <type> <description>: the JSON body (POST, PUT, PATCH), the handler's first argument;@api-response <code> [<type>] <description>: an answer (default200, JSON), one line per status;@api-tag <name>: the group (default: the module name);@api-hiddenleaves the handler out of the document;@deprecatedmarks it deprecated.
Types are lowercase words: string, integer (int), number (float),
boolean (bool), array, object; any other word starts the description, so
@api-response 404 Note not found is a status with its text.
Trying it
$ curl -s 'https://example.com/api/notes/hello?name=Ann'
)]}',
{"text":"Hello, Ann"}
$ curl -s 'https://example.com/api/notes/hello?name=Ann&callback=show'
/**/ show({"text":"Hello, Ann"});
Check the answers of every status your handler gives, a POST without the token (it must be 403), and a guest for
handlers that need a logged-in user.
A controller: yf_api_controller
For a module with several endpoints, extend yf_api_controller: it does the checks every handler above repeats. The URLs
and handler names stay the same (/api/<module>/<action> runs _api_<action>($request, $options));
you declare per action which HTTP methods it takes and which input it accepts, and the base class answers the errors. Nothing
changes for a module that does not extend it.
<?php
// modules/notes.class.php (your app's user modules folder)
load('api_controller', '', 'classes/');
class notes extends yf_api_controller
{
public $API_ACTIONS = [
'list' => ['rules' => ['page' => 'is_natural_no_zero']], // GET (and HEAD) only
'note' => [
'rules' => ['note_id' => 'required|is_natural_no_zero'], // every method of the action
'methods' => [
'get',
'post' => ['rules' => ['text' => 'trim|required|max_length[500]'], 'auth' => 'user'],
'delete' => ['auth' => 'user'],
],
],
];
/**
* Notes of the site, a page at a time.
*
* @api-tag Notes
*/
public function _api_list($request, $options)
{
$page = (int) ($request['page'] ?? 1) ?: 1;
$rows = db()->get_all('SELECT id, text FROM ' . db('notes') . ' ORDER BY id DESC LIMIT ' . (($page - 1) * 20) . ', 20');
return $this->_ok(array_values($rows), 200, ['page' => $page]);
}
public function _api_note($request, $options)
{
$id = (int) $request['note_id'];
$row = db()->get('SELECT id, user_id, text FROM ' . db('notes') . ' WHERE id = ' . $id);
if ( ! $row) {
$this->_fail(404, 'No such note');
}
if ($options['method'] === 'post') {
db()->update_safe('notes', ['text' => $request['text']], 'id = ' . $id . ' AND user_id = ' . (int) $options['principal']);
} elseif ($options['method'] === 'delete') {
db()->query('DELETE FROM ' . db('notes') . ' WHERE id = ' . $id . ' AND user_id = ' . (int) $options['principal']);
return $this->_ok(null, 204);
}
return $row;
}
}
- Methods:
methodslists them (defaultget; a GET action answers HEAD too). A method may carry its ownrules,fields,auth,csrforrate, added to the action's. Another method answers405with anAllowheader, an action the module does not have404. A public_api_handler without a declaration answers GET only. - Input: the handler's
$requestis the query string plus the body (a JSON object, or a form), the body winning.rulesare the rules ofyf_validate('trim|required|max_length[60]'); a wrong value answers422with a message per field, and filters such astrimapply to what the handler gets. Only the keys ofrulesandfieldsreach it ('strict' => falsekeeps every key). Rules are not escaping: cast and escape for the database as everywhere ((int),_es(),*_safe()). - Writes (POST, PUT, PATCH, DELETE) need the session's CSRF token (the
X-CSRF-Tokenheader or the_tokenfield, as above), checked for you; without it the answer is403.'auth' => 'user'also requires a logged-in user (401otherwise) and puts the user id in$options['principal']. - Output: return a value (sent as JSON, as a plain handler's),
$this->_ok($data, $status, $meta)for another status (201for a create,204for no body), or stop with$this->_fail($status, $message).$optionsholdsmethod(lowercase),action,authandprincipal. - Errors come as
{"error": "No such note"}, plus"fields": {"text": "..."}for a422. An exception of your code answers500with{"error": "Internal Server Error"}; its message goes to the log, never to the client. - The envelope, on request only: a client that sends
Accept: application/vnd.yf.api+json(or?envelope=1) gets{"ok": true, "data": ..., "error": null, "meta": {"api": 1, "page": 1}}, an error as{"ok": false, "data": null, "error": {"code": 422, "message": "...", "fields": {...}}, "meta": {"api": 1}}.datais exactly the plain answer, so old clients keep working and new ones read.data. A module that wants it always setspublic $ENVELOPE = true;. The)]}',line comes before both. - JSONP is off for a controller (a
callbackparameter is ignored) unless it sets$JSONP = true, and never for an action withauth. - Documented for you: the OpenAPI document of the site reads
$API_ACTIONSfrom the source when it is a plain array (methods, parameters and body fields with their types and limits, the error answers); docblock@api-*tags still win.
A working example is the demo module api_demo of the docs, a small list of items you can list,
add, change and delete: demo api/crud. Its items live in the visitor's session, never in the
database, and it answers on a demo website only (main.DEMO_WEBSITE; $PROJECT_CONF['api_demo']['ENABLED'] turns
it on or off elsewhere), so a production site does not expose it.
$ curl -s -b cookies -c cookies 'https://example.com/api/api_demo/items?per_page=2' -H 'Accept: application/vnd.yf.api+json'
)]}',
{"ok":true,"data":{"items":[{"id":1,"name":"Apples","price":"1.20"},{"id":2,"name":"Pears","price":"2.40"}],"total":3},"error":null,"meta":{"api":1,"page":1,"per_page":2,"total":3}}
$ curl -s -b cookies -X POST 'https://example.com/api/api_demo/items' -H 'Content-Type: application/json' -d '{"name":"Kiwi","price":"0.5"}'
)]}',
{"error":"CSRF token missing or invalid"}