Skip to content
Syone edited this page Nov 19, 2026 · 3 revisions

Overview

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.

Calling an endpoint

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:

1. HTTP verb

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.

2. Action / method

Url::build('api', ['content', 'valid']);
// ?p=api&a=content&a_param[0]=valid

This 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']

Create an endpoint

Option A: action on the project API controller

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.

Option B: dedicated endpoint class

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:

  1. <action>Action() on Project\Application\Api (or on Sy\Bootstrap\Application\Api);
  2. Project\Application\Api\<Action>;
  3. Sy\Bootstrap\Application\Api\<Action>;
  4. 404.

Inside a dedicated class, dispatch is:

  1. if the short class name equals the action and a_param[0] is set: <method>Action(), or <method>() as a fallback;
  2. otherwise <verb>Action(), where the verb is the lower-cased HTTP method;
  3. 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.

Responses

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, Stringable or component is rendered as-is (this is how api/feed returns HTML);
  • null produces {}.

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

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')]);
}

Security

Origin check

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',
];

Permission checks

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

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

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]=browse

This 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.

Checklist for a new endpoint

  1. Choose the surface: api for application endpoints, editor for editor integrations.
  2. Choose the style: root <action>Action() for a small utility endpoint, a dedicated class for anything with several actions or its own security rules.
  3. Implement security(): permissions, ownership, required parameters.
  4. Validate input and return requestError() with an explicit message.
  5. Return ok() / error helpers, never omit the return.
  6. Add CSRF validation if the endpoint mutates data from the web interface.
  7. Catch database exceptions and return a generic message.
  8. Test the endpoint with curl or 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'

Built-in endpoints

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

Pitfalls

  • ok(), requestError() and the other helpers do not stop the method: without return, the next statements still run.
  • 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.

Clone this wiki locally