Przejdź do treści
Biblioteka skilli
Programowanie · Integracja z narzędziem

api-routes

/api-routes

Opisuje wywołania endpointów REST addonu FriendsOfRedaxo/api: uwierzytelnianie Bearer i sesją backendu, tabela tras, schemat slice POST, endpoint /api/me, OpenAPI i diagnoza błędów 401, 404, 405 i 500.

Licencja
MIT
Ostatnia zmiana repozytorium
20.09.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
1
Przestarzałość

Brak sygnałów. Repozytorium zmienione 20.09.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Opisuje wywołania endpointów REST addonu FriendsOfRedaxo/api: uwierzytelnianie Bearer i sesją backendu, tabela tras, schemat slice POST, endpoint /api/me, OpenAPI i diagnoza błędów 401, 404, 405 i 500.

Oryginalny opis (EN)

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 `{data, meta}` list format, and a 401/404/405/500 diagnostic flow. Covers the Backend-mirror under `/api/backend/...`, multipart media upload, metainfo values for articles/categories/media/clangs, and yrewrite cache invalidation. Use when the user calls the api addon over HTTP, hits a confusing 401/404/405, syncs articles

Jak działa

  1. Activation & auth
  2. Route table (high-level)
  3. List response format
  4. Diagnostic flow (status codes)
  5. Slice schema
  6. Frontend visibility — yrewrite path cache
  7. Article metainfo
  8. OpenAPI spec
  9. Common pitfalls
Sekcje z nagłówków SKILL.md, w oryginale · 236 linii, 1 996 słów
Podgląd SKILL.md
---
name: api-routes
description: 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 `{data, meta}` list format, and a 401/404/405/500 diagnostic flow. Covers the Backend-mirror under `/api/backend/...`, multipart media upload, metainfo values for articles/categories/media/clangs, and yrewrite cache invalidation. Use when the user calls the api addon over HTTP, hits a confusing 401/404/405, syncs articles between systems via this API, builds tooling around it, or says "API-Aufruf", "REST-API ansprechen", "Bearer-Token", "Slice anlegen per API", "Artikel über API erzeugen".
---

# REDAXO `api` Addon – Calling the API (v1.2+)

The `api` addon (Repo: `FriendsOfRedaxo/api`, Vendor-NS: `FriendsOfRedaxo\Api`) exposes a RESTful API for a REDAXO backend. Auth via Bearer token *or* backend session cookie, Symfony `UrlMatcher` routing, mounted at `/api/...` via `YREWRITE_PREPARE`.

Canonical reference (always trust over this skill if they disagree): the addon `README.md` and `lib/RoutePackage/*.php`.

## Activation & auth

- Tokens are created in the backend under **AddOns → API → Token**.
- Each token has a list of **scopes** (= route names). The token can only call routes whose scope name is in the list.
- Auth header: `Authorization: Bearer <token>`
- Two auth classes:
  - `BearerAuth` — token-based frontend API (default for most routes)
  - `BackendUser` — uses the REDAXO backend session cookie. Every Bearer route is automatically mirrored under `/api/backend/...` with `BackendUser` auth and a `backend/<scope>` scope name. These routes follow the backend user's REDAXO permissions (admin / structure / media / clang / etc.) — no token needed.

### Discovery: `GET /api/me` (v1.3+)

First call against any unfamiliar instance – do not guess paths from scope names (`media/get` is `/api/media/{filename}/info`):

```bash
curl -H "Authorization: Bearer $TOKEN" https://example.org/api/me
```

- Lists **only** the endpoints whose scope the token has, with path, methods, description and parameters (`path_parameters`, `query`, `body` incl. type, `required`, default). Routes of other addons appear too.
- Needs no scope of its own (`new BearerAuth(false)`); a token without scopes sees exactly one endpoint, `me`.
- `required` follows the validation: a field without an explicit `required` key **is required**.
- `?format=openapi` returns the same set as a filtered OpenAPI 3.0 spec.
- `GET /api/backend/me` is the backend-session variant, unfiltered – permissions are checked per request, `meta.note` says so.
- `meta.auth.scopes` are the token's **stored** scopes. A scope listed there without a matching endpoint means the route no longer exists, e.g. after a rename in an update.

### Apache: pass through `Authorization`

Apache strips `Authorization` in some configurations. If the token is correct but the server returns `Authorization failed`, add to `.htaccess`:

```apache
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
```

## Route table (high-level)

Authoritative list lives in `lib/RoutePackage/*.php` (scopes) and the addon's `README.md` (paths + bodies). High-level overview of what's available in v1.2:

### Structure (articles / categories / slices)

| Method | Path                                                  | Scope                                  |
|--------|-------------------------------------------------------|----------------------------------------|
| GET    | `/api/structure/articles`                             | `structure/articles/list`              |
| GET    | `/api/structure/articles/{id}`                        | `structure/articles/get`               |
| POST   | `/api/structure/articles`                             | `structure/articles/add`               |
| PUT    | `/api/structure/articles/{id}`                        | `structure/articles/update`            |
| DELETE | `/api/structure/articles/{id}`                        | `structure/articles/delete`            |
| POST   | `/api/structure/categories`                           | `structure/categories/add`             |
| PUT    | `/api/structure/categories/{id}`                      | `structure/categories/update`          |
| DELETE | `/api/structure/categories/{id}`                      | `structure/categories/delete`          |
| GET    | `/api/structure/articles/{id}/slices`                 | `structure/articles/slices/list`       |
| GET    | `/api/structure/articles/{id}/slices/{slice_id}`      | `structure/articles/slices/get`        |
| POST   | `/api/structure/articles/{id}/slices`                 | `structure/articles/slices/add`        |
| PUT    | `/api/structure/articles/{id}/slices/{slice_id}`      | `structure/articles/slices/update`     |
| DELETE | `/api/structure/articles/{id}/slices/{slice_id}`      | `structure/articles/slices/delete`     |

### Templates / modules / clangs

GET/POST list+add, GET/PUT/DELETE on `{id}` for all three. Scopes: `templates/{list,get,add,update,delete}`, `modules/{list,get,add,update,delete}`, `system/clangs/{list,get,add,update,delete}`.

### Media

| Method | Path                                  | Scope                  |
|--------|---------------------------------------|------------------------|
| GET    | `/api/media`                          | `media/list`           |
| POST   | `/api/media` (multipart/form-data)    | `media/add`            |
| GET    | `/api/media/{filename}/info`          | `media/get`            |
| GET    | `/api/media/{filename}/file`          | `media/get/file`       |
| PUT    | `/api/media/{filename}/update`        | `media/update`         |
| DELETE | `/api/media/{filename}/delete`        | `media/delete`         |
| GET    | `/api/media/category`                 | `media/category/list`  |
| POST   | `/api/media/category`                 | `media/category/add`   |
| PUT    | `/api/media/category/{id}`            | `media/category/update`|
| DELETE | `/api/media/category/{id}`            | `media/category/delete`|

Multipart upload: send the file under field name `file` (multipart/form-data); other metadata fields (`title`, `category_id`) sit alongside as form fields. `PUT /api/media/{filename}/update` reads a replacement file from the same field name `file`.

### Chunked media upload (v1.3+)

`POST /api/media` is bound to PHP's `upload_max_filesize` / `post_max_size` (exceeding them returns `413`). Larger files go through five routes that assemble the chunks server-side and then hand the file to `rex_media_service::addMedia()` — same checks and EPs as a normal upload.

| Method   | Path                                            | Route name               | Scope          |
|----------|-------------------------------------------------|--------------------------|----------------|
| POST     | `/api/media/upload`                             | `media/upload/init`      | `media/upload` |
| GET      | `/api/media/upload/{upload_id}`                 | `media/upload/status`    | `media/upload` |
| POST/PUT | `/api/media/upload/{upload_id}/chunk/{index}`   | `media/upload/chunk`     | `media/upload` |
| POST     | `/api/media/upload/{upload_id}/finalize`        | `media/upload/finalize`  | `media/upload` |
| DELETE   | `/api/media/upload/{upload_id}`                 | `media/upload/delete`    | `media/upload` |

- **One scope for all five routes: `media/upload`.** Unlike the routes above, where the scope equals the route name, it is shared — grant `media/upload` on the token, not the five route names.
- `init` takes a JSON body `{"filename": "...", "size": <bytes>, "category_id": 0, "title": ""}` (unknown fields → 400) and answers `201` with `upload_id`, `chunk_size_max`, `max_chunks` and `expires_at`. The file extension is checked here already.
- `chunk`: send the bytes as the raw request body (`application/octet-stream`) or as multipart field `chunk`. `index` is zero-based; re-sending an index replaces that chunk. More bytes than announced at `init` → 400.
- `status` lists the received `chunks`, `bytes_missing`, `contiguous` and `complete` — use it to resume after a broken connection.
- `finalize` requires the indices to be contiguous from `0` and the total to match `size`; it answers `201 {"message": "Media created", "filename": "..."}`.
- Limits: 2 GiB per file, 20 000 chunks; an unfinished upload expires after 24 h.
- An upload is bound to the token (or backend user) that started it — any other caller gets `404 Upload not found`.
- The routes are mirrored under `/api/backend/media/upload/...` with backend-session auth, like all media routes.

### Users / roles

User CRUD on `/api/users[/{id}]` (`users/{list,get,add,update,delete}`), role CRUD on `/api/users/roles[/{id}]` (`users/roles/{list,get,add,update,delete,duplicate}`), and user↔role assignment:

- `GET /api/users/{id}/role` → `users/role/list`
- `POST /api/users/{id}/role/{role_id}` → `users/role/assign`
- `DELETE /api/users/{id}/role/{role_id}` → `users/role/remove`

### Metainfo (v1.2+)

Field definitions and value-roundtrips for the four metainfo prefixes (`art_*`, `cat_*`, `med_*`, `clang_*`):

- `GET /api/metainfo/types` → `metainfo/types/list`
- CRUD on `/api/metainfo/fields[/{id}]` → `metainfo/fields/{list,get,add,update,delete}`
- Per-resource values:
  - Articles: `GET/PUT /api/structure/articles/{id}/metainfo` → `metainfo/articles/values/{get,update}`
  - Categories: `GET/PUT /api/structure/categories/{id}/metainfo` → `metainfo/categories/values/{get,update}`
  - Media: `GET/PUT /api/media/{filename}/metainfo` → `metainfo/media/values/{get,update}`
  - Clangs: `GET/PUT /api/system/clangs/{id}/metainfo` → `metainfo/clangs/values/{get,update}` (admin-only via Backend-Session)

### Backend-mirror routes

Every Bearer route above is also exposed under `/api/backend/<original-path>` with scope `backend/<original-scope>`, authenticated via the REDAXO backend session cookie (no token needed). Permissions follow the user's REDAXO `complexPerm` settings — admins see everything, restricted users only their assigned structures/media-categories/clangs.

Use these for first-party backend tooling (a custom backend page calling its own API, for example) so you don't have to issue a token to your own backend session.

## List response format

All list endpoints return:

```json
{
  "data":  [ ... ],
  "meta":  { "page": 1, "per_page": 20, "total": 137, "total_pages": 7 }
}
```

Common query parameters on list endpoints:

- `page`, `per_page` — pagination (per_page is capped at 1000)
- `sort` — comma-separated `field:direction`, e.g. `name:asc,createdate:desc`. Each list endpoint has its own whitelist of allowed sort fields; passing an invalid one returns 400 with the allowed list.
- `filter[<field>]` — endpoint-specific filters

## Diagnostic flow (status codes)

| Status | Body                                                                     | Meaning                                                                |
|--------|--------------------------------------------------------------------------|------------------------------------------------------------------------|
| 401    | `{"error":"Authorization failed","required_scope":"users/list"}`     | Token valid and active, **scope missing** (v1.3+ adds `required_scope`) |
| 401    | `{"error":"Authorization failed"}`                                       | Token missing, wrong, or **deactivated** – `required_scope` only appears for a valid token |
| 404    | `{"error":"Route not found"}`                                            | No route matched the path                                              |
| 405    | `{"error":"Method not allowed","allowed":[...]}`                         | Path matched but the HTTP method is wrong; `allowed` lists valid ones  |
| 500    | `{"error":"Internal server error","message":"..."}`                      | Controller threw — check `var/log/system.log` for the exception        |

Quick path:

0. **`GET /api/me`** (v1.3+) → shows the token's scopes and every permitted endpoint with path and parameters, and settles "wrong path" versus "missing scope" in one call.
1. **401 `Authorization failed`** **with** `required_scope` → extend the token's scope list. **Without** it → the token is missing, wrong or deactivated (status 0). `BackendUser` route: log into the backend first.
2. **404 `Route not found`** → check path, method and trailing slash against `/api/me` or `lib/RoutePackage/*.php` before suspecting the token.
3. **405 `Method not allowed`** → use one of the methods in `allowed[]`.
4. **500 `Internal server error`** → `tail var/log/system.log` for the underlying exception. The `message` field also includes the immediate error string.
5. **HTTP 201 but frontend 404?** → yrewrite path cache stale (see below).
6. **Slice add returns 4xx / 500 with "Template has no module in such ctype"** → in the backend, check the template's module/ctype assignment.

## Slice schema

`POST /api/structure/articles/{id}/slices` body:

```json
{
  "module_id": <int, required>,
  "clang_id":  <int, required>,
  "ctype_id":  <int, default 1>,
  "value1":   "...",   "value2":   "...",   ...   "value20":   "...",
  "media1":   "...",   ...   "media10":  "...",
  "medialist1":"...", ...   "medialist10":"...",
  "link1":    "...",   ...   "link10":   "...",
  "linklist1":"...",  ...   "linklist10":"..."
}
```

One slice = one module. Which `value*` / `media*` slot maps to which editor field is defined in the module's input PHP as `REX_INPUT_VALUE[n]` / `REX_MEDIA[id=n]`.

The addon validates before insert:

- Article exists (`rex_article::get(...)`)
- Language exists (`rex_clang::getAllIds()`)
- Module exists (`rex_module`)
- **Module is allowed in the template's ctype** (`rex_template::hasModule(...)`) — otherwise the call fails. If this check fails, look at the template's ctype/module assignment in the backend.

`PUT` on a slice replaces the same fields; `DELETE` removes the slice and triggers the same EP chain as the backend page (`SLICE_DELETE` PRE → `rex_sql` delete → `SLICE_DELETED` POST → `art_content_updated`).

## Frontend visibility — yrewrite path cache

A newly-created article/category may return `404` on the frontend even with `status=1`:

- yrewrite caches URL paths in `var/cache/addon/yrewrite/...`
- `rex_article_service::addArticle()` triggers the right EPs, but yrewrite doesn't always regenerate its path cache (especially for new root categories)
- Fix: backend → **AddOns → yrewrite → Allgemein** → "Alle Caches generieren". Or in code: `rex_yrewrite::generatePathFile([])`
- There is currently **no** API endpoint for cache refresh.

## Article metainfo

Set custom metainfos (`art_*`, `cat_*`, `med_*`, `clang_*`) via the metainfo value endpoints:

```
PUT /api/structure/articles/{id}/metainfo
{ "art_color": "blue", "art_layout": "wide" }
```

Field definitions are managed via `/api/metainfo/fields` (admin-only when called via `BackendUser`; via Bearer the token needs the `metainfo/fields/*` scopes).

## OpenAPI spec

Generated from the route definitions via `OpenAPIConfig`. Two ways to get it:

- Backend: `?page=api/openapi` (Swagger UI), raw JSON with `&load_config=1` – **all** routes, needs a backend login with the `api[]` permission.
- Per token: `GET /api/me?format=openapi` (v1.3+) – **filtered** to the routes the token may call. This is the way for Postman, client generators and agents without a backend login.

Parameters and body fields carry type and default in their `schema` (v1.3+), so client generators work. What the spec lacks are response schemas: list routes answer `{data, meta}`, detail routes the flat object – see "List response format" above.

## Common pitfalls

- Adding a scope to the token that doesn't quite match the route name (e.g. `structure/article/add` vs. `structure/articles/add`) → 401 `Authorization failed`. Copy from the route source, don't re-type.
- Calling a Bearer route via the cookie session (or vice versa) → use the `/api/backend/...` mirror for backend-session calls, the plain path for Bearer.
- Building tooling that posts a slice and expects the article to be reachable on the frontend immediately → regenerate yrewrite path cache after creating articles/categories (no API endpoint exists; do it in the backend or call `rex_yrewrite::generatePathFile([])`).
- Slice POST body using `value21`, `media11`, `link11`, … — REDAXO modules only have slots 1–20 (values) / 1–10 (media/medialist/link/linklist). Extra slots are silently ignored, not validated.
- Slice POST without `module_id` + `clang_id`, or with a `module_id` that isn't allowed in the article's template/ctype → 4xx / 500 with "Template has no module in such ctype". Check the template config before retrying.
- Requesting `per_page` above 1000 — the value is silently capped at 1000, not honoured as-is. Paginate explicitly with `page=N` when you actually need more.
- Passing a `sort` field that isn't in the endpoint's whitelist → 400 with the allowed list in the body. Read that list; don't guess at `?sort=name:asc` if the endpoint only accepts e.g. `priority`/`createdate`/`updatedate`.
- 500 with no log line: check that `rex_logger` is configured and writeable; the addon logs every controller exception.
- `Authorization` header missing on Apache → add the `RewriteRule` above.

Wersje

W bazie nie ma innych skilli o nazwie api-routes.

Migawka bazy z 13.11.2026 · wersja paczki be3c6ce4aa6c (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100api-extending
    Pomaga dodawać własne trasy REST do addonu FriendsOfRedaxo/api z własnego addonu: podklasa RoutePackage, rejestracja tras, zakresy, schematy Body i query oraz zastrzeżenia kontekstu żądania.
  • 100api-docs
    Pisze dokumentację referencyjną lub specyfikację OpenAPI API na podstawie kodu źródłowego, np. listę endpointów i trasy.
  • 95backend-endpoint
    Tworzy endpoint REST lub GraphQL z walidacją, obsługą błędów i testami.
  • 90backend-api-contract
    Projektuje endpointy REST, GraphQL lub RPC: trasy, schematy żądań i odpowiedzi, błędy, uwierzytelnianie i wersjonowanie w specyfikacji OpenAPI.
  • 100api-generating
    Generuje kod i dokumentację endpointów API ze specyfikacji: nowe endpointy, handlery tras, szkielety REST API i specyfikacje OpenAPI lub Swagger z kodu.
  • 100api-design
    Projektuje kontrakty REST, GraphQL i OpenAPI przed implementacją w podejściu API-first.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.