/redaxo-api-addon:api-extendingfrom redaxo-api-addon
Adds custom REST routes to the FriendsOfRedaxo/api addon (v1.2+) from your own addon. Covers RoutePackage subclass, route registration, scope management, Body/query schema keys, and request-context caveats like auth running in frontend context.
Ships in redaxo-api-addon. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
api Addon (v1.2+)You can add your own routes to the api addon from any custom addon. They reuse the same Bearer token, the same scope mechanism, the same OpenAPI generator, and the same JsonResponse-based response convention as the built-in routes.
<?php
namespace MyVendor\MyAddon\RoutePackage;
use FriendsOfRedaxo\Api\Auth\BearerAuth;
use FriendsOfRedaxo\Api\RouteCollection;
use FriendsOfRedaxo\Api\RoutePackage;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Route;
class MyResource extends RoutePackage
{
public function loadRoutes(): void
{
RouteCollection::registerRoute(
'myaddon/things/list', // becomes the token scope name
new Route(
'myaddon/things', // → /api/myaddon/things
[
'_controller' => self::class . '::handleList',
'query' => [ // GET parameter schema
'page' => ['type' => 'integer', 'default' => 1],
'per_page' => ['type' => 'integer', 'default' => 20],
'sort' => ['type' => 'string'],
'filter' => ['type' => 'object', 'properties' => [
'name' => ['type' => 'string'],
]],
],
],
[], [], '', [], ['GET'],
),
'List things', // OpenAPI summary
null, // custom response definitions, or null
new BearerAuth(),
);
RouteCollection::registerRoute(
'myaddon/things/add',
new Route(
'myaddon/things',
[
'_controller' => self::class . '::handleAdd',
'Body' => [ // POST/PUT body schema (note the capital B)
'name' => ['type' => 'string', 'required' => true],
'color' => ['type' => 'string', 'default' => 'blue'],
],
],
[], [], '', [], ['POST'],
),
'Create a thing',
null,
new BearerAuth(),
);
}
public static function handleList($Parameter): Response
{
$Query = RouteCollection::getQuerySet($_REQUEST, $Parameter['query']);
// ... build response data ...
return new JsonResponse(['data' => [/* ... */], 'meta' => [/* ... */]]);
}
public static function handleAdd($Parameter): Response
{
$Body = json_decode(\rex::getRequest()->getContent(), true);
try {
$Data = RouteCollection::getQuerySet($Body, $Parameter['Body']);
} catch (\Throwable $e) {
return new JsonResponse(['error' => 'Body field: `' . $e->getMessage() . '` is required'], 400);
}
$id = 0; // ... persist, e.g. $id = (int) $sql->getLastId() ...
return new JsonResponse(['message' => 'Thing created', 'id' => $id], 201);
}
}
Both query and Body are validated/normalized by RouteCollection::getQuerySet() against the schema you declared on the route — don't re-validate manually.
boot.php\FriendsOfRedaxo\Api\RouteCollection::registerRoutePackage(
new \MyVendor\MyAddon\RoutePackage\MyResource()
);
After registration, the new scope (myaddon/things/list) appears in the backend token editor. Add it to the relevant token, otherwise calls return Authorization failed.
Stay consistent: pick either trailing-slash or no-trailing-slash per resource and keep all methods on that resource using the same convention. The built-in routes converged on no trailing slash in v1.2 — recommend the same in your own RoutePackages:
'myaddon/things' // GET → list
'myaddon/things' // POST → create
'myaddon/things/{id}' // GET → show
'myaddon/things/{id}' // PATCH → update
'myaddon/things/{id}' // DELETE → remove
| Class | Use for |
|---|---|
BearerAuth | Standard token-based API |
BackendUser | Routes that should only be callable when logged into the backend (cookie session) |
null | Unauthenticated public endpoint — only do this for actually public data |
new BearerAuth(false) | Any valid, active token without a scope check (v1.3+) – for self-describing endpoints like /api/me only; Auth::requiresScope() keeps such routes out of the token page's scope list. Everything that reads or writes data stays on new BearerAuth() |
Prefer BearerAuth for external-facing endpoints. For internal backend tools, mirror your Bearer routes under backend/<scope> with BackendUser auth — that's the convention used by the built-in Backend/* packages, see lib/RoutePackage/Backend/Clangs.php for a tiny reference implementation that clones every Bearer route from a parent package and re-registers it with BackendUser.
RouteCollection::handle() runs in the frontend user context (specifically: it dispatches inside YREWRITE_PREPARE, before any backend bootstrapping). Three consequences:
rex::isBackend() returns false in API calls — even on BackendUser routes. Code paths gated on rex::isBackend() silently skip.if (rex::isBackend()) { ... } branches don't fire. Either register them unconditionally and guard inside the callback, or trigger them explicitly inside the API route.rex::getUser() is null on Bearer routes. Some REDAXO PRE-extension-points (notably SLICE_UPDATE, SLICE_DELETE, parts of structure-management) call rex::requireUser() internally. Calling those service methods from an API route that authenticated via Bearer will throw. Two options:
rex::getUser() !== null (i.e. only on BackendUser routes).Structure::handleUpdateArticleSlice / handleDeleteArticleSlice do.When porting backend logic to an API endpoint, audit every rex::isBackend(), rex::getUser(), and rex::requireUser() check in the call path.
The built-in routes follow a hard rule (see the addon's CLAUDE.md): the API is not a parallel system, it's an HTTP frontend for the existing backend pages. If a backend page (pages/*.php) calls rex_article_service::editArticle() and then fires STRUCTURE_CONTENT_ARTICLE_UPDATED and clears rex_article_cache::delete($id), the API route does the same — same calls, same EP names, same parameter keys, same order, same cache invalidation. Don't:
MY_THING_DELETED if the equivalent backend page is silent)This rule applies equally to your custom RoutePackages if you're wrapping core resources.
Use Symfony\Component\HttpFoundation\JsonResponse (the built-in routes converged on this in #18). It sets Content-Type: application/json automatically and serialises arrays for you — $items, $meta and $id below stand for whatever your handler computed:
return new JsonResponse(['data' => $items, 'meta' => $meta], 200);
return new JsonResponse(['message' => 'Thing created', 'id' => $id], 201);
return new JsonResponse(['message' => 'Thing deleted', 'id' => $id], 200);
return new JsonResponse(['error' => 'Bad request'], 400);
For consistency with the built-in routes:
{"message": "… created", "id": …} for successful creates (slices return slice_id, media filename instead of id){"message": "… deleted", "id": …} for successful deletes — no built-in route answers 204GET /api/structure/articles/{id} or GET /api/templates/{id} return the object itself, without a data wrapper; {data, meta} is the list envelope{"error": "..."} for client errors (extra context fields are fine){"error": "..."} only after logging the underlying exception (RouteCollection already wraps unhandled throwables with rex_logger::logException)For paginated lists, use ListHelper::paginate() / ListHelper::wrapResponse() to get the standard {data, meta} envelope used by every built-in list endpoint.
The addon generates an OpenAPI spec at ?page=api/openapi from registered routes. The third and fourth arguments to registerRoute() (description + custom responses) feed that generator. Spend a minute writing a meaningful description — Swagger UI uses it.
The query and Body schemas you declare in _controller are mirrored into the spec automatically — that's why they live in the route definition and not just inside the handler. They also show up in GET /api/me (v1.3+) for every token that holds the route's scope, so keep them accurate.
Declare file uploads as 'type' => 'file' – the spec then switches the request body to multipart/form-data with format: binary; a file field declared as string appears as a JSON field. Own tags need the language key api_openapi_tag_<tag>_description (OpenAPIConfig), otherwise the tag description stays empty.
boot.php — the route never appears, calls return 404 Route not found.Authorization failed.RouteCollection::registerRoute() defaults to null, and RouteCollection::handle() only checks authorization when an auth object is set (// if no AuthObject is set, we assume that the route is public). Drop the trailing new BearerAuth() from the skeleton and the handler runs for any anonymous request. Nothing warns you: the token editor only lists scopes of BearerAuth routes, so the scope simply doesn't appear, and the OpenAPI spec shows the route with an empty security. Always pass an auth object; use null only for data that is meant to be public.new Response(json_encode(...)) and forgetting Content-Type: application/json — use JsonResponse instead, that's the addon convention since #18.$_POST — JSON bodies aren't in $_POST. Use json_decode(rex::getRequest()->getContent(), true)._controller instead of Class::method references — Symfony's UrlMatcher doesn't serialize closures cleanly across the routing layer.rex::getUser() from a Bearer route — wrap the EP-firing in a null !== rex::getUser() guard or replicate the service logic in your handler.RouteCollection catches and logs, but you lose the structured error message. For business-logic errors, return JsonResponse(['error' => '…'], 4xx) directly.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub friendsofredaxo/claude-marketplace --plugin redaxo-api-addon2 skills in this plugin
Other plugins' skills for the same job