Repository navigation
API
The framework exposes two HTTP surfaces built on Sy\Bootstrap\Component\Api:
| Surface | Controller | Action classes | Usage |
|---|---|---|---|
p=api |
Project\Application\Api or Sy\Bootstrap\Application\Api
|
...\Application\Api\<Action> |
Application endpoints (pages, articles, contents, avatar, feed, CSRF) |
p=editor |
Sy\Bootstrap\Application\Editor |
Sy\Bootstrap\Application\Editor\<Action> |
CKEditor and administration endpoints (browse, upload) |
Both are WebComponents: they dispatch the request in their mount hook and write the result through a {RESPONSE} template.
The URL is built from three request parameters:
| Constant | Parameter | Role |
|---|---|---|
CONTROLLER_TRIGGER |
p |
api or editor
|
ACTION_TRIGGER |
a |
Action name, converted to CamelCase |
ACTION_PARAM |
a_param |
Ordered parameters; the first one is the method |
Two call styles are supported:
Url::build('api', 'page', ['id' => $name, 'lang' => $lang]);
// ?p=api&a=page&id=...&lang=...The sub-controller is called according to the HTTP method: getAction() for GET, postAction() for POST, deleteAction() for DELETE, and so on.
Url::build('api', ['content', 'valid']);
// ?p=api&a=content&a_param[0]=validThis calls validAction() on the Content class. Remaining a_param values are available in $this->param (protected, so only inside the class):
Url::build('api', ['ping', 'detail', '42']);
// ?p=api&a=ping&a_param[0]=detail&a_param[1]=42
// => Ping::detailAction(), $this->param === ['42']Add a public method named <action>Action() to Project\Application\Api:
<?php
namespace Project\Application;
class Api extends \Sy\Bootstrap\Application\Api {
public function pingAction() {
return $this->ok([
'status' => 'ok',
'message' => 'pong',
]);
}
}Call it with Url::build('api', 'ping'). Root actions are resolved first, so they take precedence over a class with the same name.
Create a class in Project\Application\Api (the framework namespace Sy\Bootstrap\Application\Api works too, but project classes should stay in the project):
<?php
namespace Project\Application\Api;
class Ping extends \Sy\Bootstrap\Component\Api {
public function security() {
// Throw an exception to reject the request
}
public function getAction() {
return $this->ok([
'status' => 'ok',
'message' => 'pong',
'time' => time(),
]);
}
}Call it with Url::build('api', 'ping') and a GET request. The class name determines the URL: Ping is reached through a=ping.
Resolution order for p=api:
-
<action>Action()onProject\Application\Api(or onSy\Bootstrap\Application\Api); -
Project\Application\Api\<Action>; -
Sy\Bootstrap\Application\Api\<Action>; -
404.
Inside a dedicated class, dispatch is:
- if the short class name equals the action and
a_param[0]is set:<method>Action(), or<method>()as a fallback; - otherwise
<verb>Action(), where the verb is the lower-cased HTTP method; - unknown method:
404.
Plugins add endpoints by creating a class under Sy\Bootstrap\Application\Api\ (for example bootstrap-article provides Article, bootstrap-cms provides Content and ContentTranslation). No registration is needed.
Component\Api does not impose a response format. response($code, $data) sets the HTTP status, then:
- an array is JSON-encoded with
Content-Type: application/json; - a non-empty string,
Stringableor component is rendered as-is (this is howapi/feedreturns HTML); -
nullproduces{}.
JSON is the de facto standard for API calls, but it is a usage convention, not an enforced contract.
| Helper | Status | Typical use |
|---|---|---|
ok($data) |
200 | Success |
requestError($data) |
400 | Missing or invalid parameter |
forbidden($data) |
403 | Permission denied |
notFound($data) |
404 | Unknown resource or action |
serverError($data) |
500 | Unexpected failure |
These helpers only set the response; they do not stop execution. Always return them:
public function getAction() {
if (is_null($this->get('id'))) {
return $this->requestError([
'status' => 'ko',
'message' => 'Missing id parameter',
]);
}
return $this->ok([
'status' => 'ok',
'id' => $this->get('id'),
]);
}A response can also be a component:
public function getAction() {
return $this->ok(new \Project\Component\MyFragment());
}Exceptions thrown from security() or from an action are converted into responses:
| Exception | Response |
|---|---|
Sy\Bootstrap\Component\Api\NotFoundException |
404 |
Sy\Bootstrap\Component\Api\ForbiddenException |
403 |
Sy\Bootstrap\Component\Api\RequestErrorException |
400 |
any other Throwable
|
500 |
Throwing is usually cleaner than returning an error from security():
public function security() {
if (is_null($this->request('id'))) {
throw new \Sy\Bootstrap\Component\Api\RequestErrorException('Missing id parameter');
}
$service = \Project\Service\Container::getInstance();
if (!$service->user->getCurrentUser()->hasPermission('content-update')) {
throw new \Sy\Bootstrap\Component\Api\ForbiddenException('Permission denied');
}
}Because unhandled exceptions are returned with $e->getMessage(), catch expected exceptions and return a generic message instead of exposing internals:
try {
// ...
} catch (\Sy\Db\MySql\Exception $e) {
$this->logError($e);
return $this->serverError(['status' => 'ko', 'message' => $this->_('Database error')]);
}Application\Api and Application\Editor require an HTTP_ORIGIN (or HTTP_REFERER) whose host matches SERVER_NAME. This rejects cross-site calls from a browser but is not an authentication mechanism: the user session is still the source of identity.
The project can bypass the check for specific routes through the $whiteList property of Project\Application\Api:
private $whiteList = [
'ping/get',
];Each endpoint implements security() for its own rules. A dedicated class replaces the root security(), but the origin check has already run at the root controller.
CSRF is not enforced by the API layer. It is a recommendation for endpoints called from the web interface on behalf of a logged-in user, where the request is the equivalent of a form submission. Endpoints consumed by scripts or service calls generally do not need it.
The usual pattern:
public function postAction() {
$service = \Project\Service\Container::getInstance();
if ($this->post('csrf') !== $service->user->getCsrfToken()) {
return $this->requestError([
'status' => 'ko',
'message' => $this->_('You have taken too long to submit the form please try again'),
'csrf' => $service->user->getCsrfToken(),
]);
}
// Handle the request...
}Returning the current token lets the client update its form and retry without reloading the page (see api/csrf and Component\Form\Csrf.js).
Current coverage:
| Endpoint | CSRF |
|---|---|
api/avatar (POST) |
yes, __csrf field |
api/page, api/article, api/content (POST) |
yes, csrf field |
api/content-translation (POST) |
no |
api/flash-message (DELETE) |
no |
Editor endpoints use the same base component. Application\Editor checks the origin, then loads a class from Sy\Bootstrap\Application\Editor\<Action> when it exists, and falls back to its own verb actions.
The CkFile trait provides the CKEditor integration:
Url::build('editor', 'content/browse', ['id' => $id, 'type' => 'image']);
// p=editor&a=content&a_param[0]=browseThis loads Sy\Bootstrap\Application\Editor\Content and calls browseAction(). The same class exposes uploadAction(). Plugins provide their own classes (Editor\Article for bootstrap-article, Editor\Content for bootstrap-cms), each with its own permission check.
- Choose the surface:
apifor application endpoints,editorfor editor integrations. - Choose the style: root
<action>Action()for a small utility endpoint, a dedicated class for anything with several actions or its own security rules. - Implement
security(): permissions, ownership, required parameters. - Validate input and return
requestError()with an explicit message. - Return
ok()/ error helpers, never omit thereturn. - Add CSRF validation if the endpoint mutates data from the web interface.
- Catch database exceptions and return a generic message.
- Test the endpoint with
curlor the browser network panel.
curl -i 'https://example.com/?p=api&a=ping'
curl -i -X POST 'https://example.com/?p=api&a=ping' -d 'name=foo'| Endpoint | Class | Verbs |
|---|---|---|
api/csrf |
Application\Api::csrfAction |
GET |
api/feed |
Application\Api::feedAction |
GET |
api/avatar |
Application\Api::avatarAction |
POST |
api/page |
Application\Api\Page |
GET, POST |
api/flash-message |
Application\Api\FlashMessage |
GET, DELETE |
api/article |
bootstrap-article Api\Article
|
GET, POST |
api/content |
bootstrap-cms Api\Content
|
GET, POST |
api/content-translation |
bootstrap-cms Api\ContentTranslation
|
GET, POST |
api/location |
bootstrap-location Api\Location
|
GET |
editor/<action>/browse, editor/<action>/upload
|
Application\Editor, plugin Editor\*
|
GET, POST |
-
ok(),requestError()and the other helpers do not stop the method: withoutreturn, the next statements still run and can overwrite the response. - Unknown methods fall back to
__call()→ 404, which hides typos in method names. - URLs are derived from class names: renaming an API class changes its public route.
- Response shapes are not standardized (
{status, content},{csrf}, plain strings, HTML fragments); keep a single shape per endpoint. - There is no authentication built in: the user session and
security()decide who can call what. - Only verb dispatch is covered by tests (
tests/Component/ApiTest.php); routing and security have no test coverage.