Internal and public API
The CMS has two API surfaces, similar in name and unrelated to each other. Mixing them up is the first mistake.
1. The two surfaces
| Internal REST | Public API | |
|---|---|---|
| URL | /api/<version>/... | /api/1.0/<endpoint> |
| Who answers | conf/gallery/api/* via the kernel (Api::request) | physical folder api/1.0/index.php |
| For whom | the CMS backend and front end (internal AJAX) | external integrators, machine-to-machine |
| Authentication | CMS session and permissions | client credentials → Bearer token |
| Status in the repo | inherited from upstream, used by the backend | written for JoeCMS, only the auth endpoint |
The conflict is real: /api is reserved by the kernel (vendor/wolfgan/cms/services/kernel.php routes /api/... to Api::request), so a public API can't be routed via routing_table.xml. The adopted solution is a physical folder served directly by Apache.
/api is reserved only as the first segment: the kernel's two API rules ('^/api/1.0/', '^/api(?=/|$)…') and the api rule in conf/routing_table.xml are anchored, like the system folder ones (01 §3). Up to 3.1.0 they weren't, and any path containing /api ended up in Api::request() with an empty 404: a module's APIs under /jd/api/…, a backoffice service /srv/progetto/api-rigenera, a page /apicoltura. On a site still on 3.1.0 the old advice holds: no /api inside paths.
2. Internal REST: what it already exposes
conf/gallery/api/ (routed by conf/routing_table.xml, rule id="api"):
| Endpoint | Returns |
|---|---|
get_user, get_anagraph, get_anagraph_rel_anagraph | users and registry records |
get_form, get_form_fields, get_form_type, get_form_revision | form definitions and revisions |
get_vgallery_type, get_vgallery_fields, get_extended_type | the content schema at runtime |
get_layout | layout structure |
get_operation, get_payment | operations and e-commerce |
process_list, process_detail, process_updater | lists, detail, update |
parse | template parsing |
notifier/ | notifications (see 06) |
get_vgallery_type + get_vgallery_fields + get_extended_type are why a generator can be generic: the content schema can be read at runtime, without knowing in advance which types exist on that installation. That's exactly what /md does for the Markdown version of content (GUIDA_INDICIZZAZIONE_AI.md).
3. Public API: how it's built
Full detail and operational reference in ../api-auth.md. Here's the model, for those who need to extend it.
GET/POST /api/1.0/<endpoint>[/<resource>/…]
└─ api/1.0/.htaccess HTTPS + Authorization → PHP-FPM
rewrite ?_ep=<endpoint>[&_path=<resource/…>]
▼
api/1.0/index.php minimal bootstrap (livello-errori, config, autoload, cache, ff/main, hook)
├─ whitelist: "auth" + JC_API_ENDPOINTS
└─ include applets/services/api/<endpoint>.php
The rest of the path after the endpoint arrives in $_GET["_path"] (cleaned: only letters, digits, _, -, /). It's for endpoints exposing several resources — /api/1.0/app/bookings/cancel — and those that don't use it ignore it.
The authentication flow:
POST /api/1.0/auth {client_id, client_secret}
→ {ok, token_type:"Bearer", access_token:"joe_<64hex>", expires_in:3600, expires_at}
→ Authorization: Bearer joe_<...> on every following call
- credentials in
cm_api_client, tokens incm_api_token(stored as SHA-256); - constant TTL
JOECMS_API_TOKEN_TTL(3600s), no refresh token: for machine-to-machine the client re-authenticates; - generating credentials from the CLI:
php install/api-credenziali.php "Client name".
Adding an endpoint
- create
applets/services/api/<ep>.php; - declare it in the installation config, without touching
api/1.0/index.php:define("JC_API_ENDPOINTS", "<ep>"); // more than one: "app,webhook"authis always there and needn't be listed. This step used to be a change to the front controller, i.e. to the core: every project left the name of one of its endpoints there; - protect it:
$ctx = joecms_api_auth(); // reads Authorization: Bearer
if (!$ctx) { joecms_api_json(401, array("ok" => false, "error" => "unauthorized")); }
$id_client = $ctx["ID_client"];
$body = joecms_api_body(); // JSON, fallback $_POST
// ... logic ...
joecms_api_json(200, array("ok" => true));
The helpers (joecms_api_has_schema, joecms_api_genera_credenziali, joecms_api_client_by_credentials, joecms_api_crea_token, joecms_api_auth, joecms_api_read_bearer, joecms_api_body, joecms_api_json, joecms_api_uuid) live in hook.php.
4. Contract conventions
Few, repeated everywhere: it's the part the integrator perceives as a "consistent API".
Content-Type: application/json, with transparent fallback to form parameters.- Every response has a boolean
ok. Error ={ok:false, error:"<code or message>"}. - Unknown keys are not an error: they're collected into an
ignoratiarray in the response. A client sending an extra field doesn't get the whole call rejected, but notices. - Partial update: upserts only touch fields present in the body. Absent ≠ empty.
- Idempotency where it's free: deleting something that isn't there answers 200 with
deleted:false. A client retry must never be dangerous. - Fields the API can't write are declared in the docblock and silently ignored: it's the surface that protects the domain's invariants.
HTTP status codes, with the meaning used in the ecosystem:
| Code | When |
|---|---|
| 200 | done (also for "there was nothing to do") |
| 202 | accepted, the effect comes later (queue) |
| 400 | empty or non-JSON body, missing or invalid parameter |
| 401 | missing, unknown or expired token — and also wrong credentials on /auth |
| 403 | authenticated but not authorised on that resource |
| 404 | endpoint not in the whitelist |
| 422 | formally valid request that can't be executed in the current state |
| 429 | rate limit |
| 503 | migration not applied on this installation |
The 503 for missing schema is a pattern worth copying: joecms_api_has_schema() checks the tables and the endpoint answers 503 api_schema_missing instead of hitting a fatal error. A half-done deploy diagnoses itself.
5. Pitfalls already paid for
Authorizationdisappears with PHP-FPM. You need both theE=HTTP_AUTHORIZATIONrule in the.htaccessand the fallbacks injoecms_api_read_bearer(). Classic symptom: works locally, 401 in production.mod_rewritedoesn't inherit from the parent: HTTPS and rewrites must be repeated in the folder's.htaccess.mod_headersinstead adds up (the root CORS stays valid).chdir($root)in the front controller:config.phpuses relativerequires; withoutchdirthe bootstrap fails obscurely.- Compare the secret with
hash_equals, and make the 401 indistinguishable between a non-existent client and a wrong secret: otherwise the API becomes an oracle for enumerating clients. - The tenant is never accepted from the body. It's the mistake that turns the API into an open door on other people's data.
use_cache(false)at the top of every service file: without it, the CMS may serve a cached response to an authenticated call.- Targeted token housekeeping: a global
DELETEonexpires_at < NOW()on every auth becomes expensive on large tables. - Whitelist and documentation diverge silently. If the API grows, you need an automatic check comparing whitelist, files present and documentation.
- The
api/folder must be uploaded by hand in deploys without a ZIP: it's outside the kernel flow and therefore outside people's attention.
6. Giving the API a face
Without a place to read client_id and client_secret, for the customer the API doesn't exist. The proven pattern is a tab in the backend settings with:
- credentials, with copy / show / regenerate;
- the list of available endpoints;
- the table of accepted parameters generated from the real fields of that installation — documentation that can't diverge from the system;
curlexamples ready to paste, with the real host.
The regeneration service is backoffice, not API: session authentication (checkUserRights), ownership check, then regeneration. And — see §1 — no api in the path name.