Skip to content
JoeCMS Download 3.1.5
Manual · 04

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 RESTPublic API
URL/api/<version>/.../api/1.0/<endpoint>
Who answersconf/gallery/api/* via the kernel (Api::request)physical folder api/1.0/index.php
For whomthe CMS backend and front end (internal AJAX)external integrators, machine-to-machine
AuthenticationCMS session and permissionsclient credentials → Bearer token
Status in the repoinherited from upstream, used by the backendwritten 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"):

EndpointReturns
get_user, get_anagraph, get_anagraph_rel_anagraphusers and registry records
get_form, get_form_fields, get_form_type, get_form_revisionform definitions and revisions
get_vgallery_type, get_vgallery_fields, get_extended_typethe content schema at runtime
get_layoutlayout structure
get_operation, get_paymentoperations and e-commerce
process_list, process_detail, process_updaterlists, detail, update
parsetemplate 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 in cm_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

  1. create applets/services/api/<ep>.php;
  2. declare it in the installation config, without touching api/1.0/index.php:
    define("JC_API_ENDPOINTS", "<ep>");          // more than one: "app,webhook"

    auth is 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;

  3. 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 ignorati array 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:

CodeWhen
200done (also for "there was nothing to do")
202accepted, the effect comes later (queue)
400empty or non-JSON body, missing or invalid parameter
401missing, unknown or expired token — and also wrong credentials on /auth
403authenticated but not authorised on that resource
404endpoint not in the whitelist
422formally valid request that can't be executed in the current state
429rate limit
503migration 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

  • Authorization disappears with PHP-FPM. You need both the E=HTTP_AUTHORIZATION rule in the .htaccess and the fallbacks in joecms_api_read_bearer(). Classic symptom: works locally, 401 in production.
  • mod_rewrite doesn't inherit from the parent: HTTPS and rewrites must be repeated in the folder's .htaccess. mod_headers instead adds up (the root CORS stays valid).
  • chdir($root) in the front controller: config.php uses relative requires; without chdir the 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 DELETE on expires_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;
  • curl examples 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.