api-extending
/api-extending
Adding custom REST routes to the FriendsOfRedaxo/api addon (v1.2+) from your own addon — building a RoutePackage subclass, registering routes, scope management, the `Body`/`query` schema keys, request-context caveats (auth runs in frontend context, isBackend() returns false, PRE-EPs that call rex::requireUser() fail under Bearer), and the addon's exact-mirror-of-core convention. Use when the user adds endpoints to the api addon, exposes their own data over the same auth/scope mechanism, runs into "EP fires only in backend but I need it from the API" / "rex::requireUser threw" problems, or says
- Author
- friendsofredaxo ↗
- Repository
- claude-marketplace ↗
- Licence
- MIT
- Last repository change
- 20.09.2026
Assessment and security
- Files in this package
- 1
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 0
No signals detected. Repository changed on 20.09.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
What it does and when to use it
Adding custom REST routes to the FriendsOfRedaxo/api addon (v1.2+) from your own addon — building a RoutePackage subclass, registering routes, scope management, the `Body`/`query` schema keys, request-context caveats (auth runs in frontend context, isBackend() returns false, PRE-EPs that call rex::requireUser() fail under Bearer), and the addon's exact-mirror-of-core convention. Use when the user adds endpoints to the api addon, exposes their own data over the same auth/scope mechanism, runs into "EP fires only in backend but I need it from the API" / "rex::requireUser threw" problems, or says
Triggers from the description
Original author description
Adding custom REST routes to the FriendsOfRedaxo/api addon (v1.2+) from your own addon — building a RoutePackage subclass, registering routes, scope management, the `Body`/`query` schema keys, request-context caveats (auth runs in frontend context, isBackend() returns false, PRE-EPs that call rex::requireUser() fail under Bearer), and the addon's exact-mirror-of-core convention. Use when the user adds endpoints to the api addon, exposes their own data over the same auth/scope mechanism, runs into "EP fires only in backend but I need it from the API" / "rex::requireUser threw" problems, or says
How it works
- RoutePackage skeleton
- Register in the addon's boot.php
- Trailing-slash convention
- Authentication options
- Request context caveats
- Mirror REDAXO-core behaviour exactly
- Returning the right response shape
- OpenAPI integration
- Common pitfalls
SKILL.md preview
---
name: api-extending
description: Adding custom REST routes to the FriendsOfRedaxo/api addon (v1.2+) from your own addon — building a RoutePackage subclass, registering routes, scope management, the `Body`/`query` schema keys, request-context caveats (auth runs in frontend context, isBackend() returns false, PRE-EPs that call rex::requireUser() fail under Bearer), and the addon's exact-mirror-of-core convention. Use when the user adds endpoints to the api addon, exposes their own data over the same auth/scope mechanism, runs into "EP fires only in backend but I need it from the API" / "rex::requireUser threw" problems, or says "eigene Route registrieren", "API um eigenen Endpunkt erweitern", "RoutePackage bauen".
---
# Extending the `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.
## RoutePackage skeleton
```php
<?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.
## Register in the addon's `boot.php`
```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`.
## Trailing-slash convention
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:
```php
'myaddon/things' // GET → list
'myaddon/things' // POST → create
'myaddon/things/{id}' // GET → show
'myaddon/things/{id}' // PATCH → update
'myaddon/things/{id}' // DELETE → remove
```
## Authentication options
| 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`.
## Request context caveats
`RouteCollection::handle()` runs in the **frontend user context** (specifically: it dispatches inside `YREWRITE_PREPARE`, before any backend bootstrapping). Three consequences:
1. **`rex::isBackend()` returns `false`** in API calls — even on `BackendUser` routes. Code paths gated on `rex::isBackend()` silently skip.
2. **Extension points registered only in `if (rex::isBackend()) { ... }` branches don't fire.** Either register them unconditionally and guard inside the callback, or trigger them explicitly inside the API route.
3. **`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:
- Guard the EP yourself: only call the service method or fire the EP when `rex::getUser() !== null` (i.e. only on `BackendUser` routes).
- Bypass the service and replicate the relevant SQL + the POST-EP yourself, the way the built-in `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.
## Mirror REDAXO-core behaviour exactly
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:
- Invent EPs that core doesn't fire (e.g. don't fire a custom `MY_THING_DELETED` if the equivalent backend page is silent)
- Add fields to the EP payload that core doesn't set
- Skip cache invalidation that the backend page does
This rule applies equally to your custom RoutePackages if you're wrapping core resources.
## Returning the right response shape
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:
```php
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:
- **200** for successful reads
- **201** with `{"message": "… created", "id": …}` for successful creates (slices return `slice_id`, media `filename` instead of `id`)
- **200** with `{"message": "… deleted", "id": …}` for successful deletes — no built-in route answers 204
- Single-resource reads such as `GET /api/structure/articles/{id}` or `GET /api/templates/{id}` return the object itself, without a `data` wrapper; `{data, meta}` is the list envelope
- **4xx** with `{"error": "..."}` for client errors (extra context fields are fine)
- **5xx** with `{"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.
## OpenAPI integration
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.
## Common pitfalls
- Forgetting to register the RoutePackage in `boot.php` — the route never appears, calls return 404 `Route not found`.
- Forgetting to add the new scope to the token in the backend — calls return 401 `Authorization failed`.
- **Omitting the auth argument makes the route public (fail-open).** The fifth parameter of `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.
- Using `new Response(json_encode(...))` and forgetting `Content-Type: application/json` — use `JsonResponse` instead, that's the addon convention since #18.
- Reading bodies via `$_POST` — JSON bodies aren't in `$_POST`. Use `json_decode(rex::getRequest()->getContent(), true)`.
- Using closures in `_controller` instead of `Class::method` references — Symfony's `UrlMatcher` doesn't serialize closures cleanly across the routing layer.
- Calling a service method that internally fires a PRE-EP requiring `rex::getUser()` from a Bearer route — wrap the EP-firing in a `null !== rex::getUser()` guard or replicate the service logic in your handler.
- Throwing exceptions and assuming the framework will format them — yes, `RouteCollection` catches and logs, but you lose the structured error message. For business-logic errors, return `JsonResponse(['error' => '…'], 4xx)` directly.
Versions
The database has no other skills named api-extending.
Database snapshot: 13.11.2026 · package version f0598741a6cf (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 100api-routes
Calling the FriendsOfRedaxo/api REST endpoints (v1.2+) — Bearer + Backend-Session auth, the route table for articles/categories/slices/modules/templates/languages/media/users/metainfo, the slice POST schema, the `/api/me` discovery endpoint (v1.3+), OpenAPI spec, the unified… - 100redaxo-api-functions
Building HTTP/AJAX endpoints in REDAXO using rex_api_function – the lib/ class location, naming convention, $published flag for frontend access, JSON responses, CORS for cross-domain widgets, and the rex-api-call URL. Use when the user adds an AJAX/HTTP endpoint to a custom… - 100scaffold-addon
Create a complete addon package structure inside agentic/code/addons/. Use when authoring an expansion (addon) for AIWG. - 90wp-rest-api
Use when building, extending, or debugging WordPress REST API endpoints/routes: register_rest_route, WP_REST_Controller/controller classes, schema/argument validation, permission_callback/authentication, response shaping, register_rest_field/register_meta, or exposing… - 100wp-rest-api-development
WordPress REST API review and development guidance. Use when reviewing custom REST routes, permission_callback logic, schema design, WP_REST_Request handling, response structure, versioning, controller classes, nonce or auth usage, or when user mentions "REST API review",… - 90wp-rest-api
Use when building, extending, or debugging WordPress REST API endpoints/routes: register_rest_route, WP_REST_Controller/controller classes, schema/argument validation, permission_callback/authentication, response shaping, register_rest_field/register_meta, or exposing…