GraphQL API reference
What this is. The complete reference of the GraphQL API of the Exponential kernel: the end points, the request and answer formats, every root query, mutation and subscription with its arguments, the types, pagination, filtering, sorting, languages, persisted queries and every error code. The GraphQL shape of each datatype is on its own page, Datatypes in GraphQL.
When to use it. Whenever you write a query or a mutation, handle an error, or need to know exactly what an argument does.
Quick example (curl, plain fetch, the SDK):
EXP=https://www.example.com
curl -s "$EXP/api/graphql" -H 'Content-Type: application/json' \
-d '{"query":"query Page($alias: String!) { node(urlAlias: $alias) { name url } }","variables":{"alias":"recipes"}}'const res = await fetch('https://www.example.com/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: 'query Page($alias: String!) { node(urlAlias: $alias) { name url } }',
variables: { alias: 'recipes' },
}),
});
const { data, errors } = await res.json();import { createClient, gql } from '@exponentialcms/client';
const client = createClient({ url: 'https://www.example.com' });
const Page = gql<{ node: { name: string; url: string | null } | null }, { alias: string }>`
query Page($alias: String!) { node(urlAlias: $alias) { name url } }
`;
const { node } = await client.request(Page, { alias: 'recipes' });Every example on this page runs against any installation with the API switched on; class-specific fields use the
classes of the media site (ng_article, ng_recipe ...): put your own class identifiers there.
Contents
- End points and HTTP
- The answer
- Your first query, three ways
- Variables, operation names, aliases and fragments
- Root queries
- The Content interface and the class types
- The Location type
- Lists and pagination
- Filtering and sorting
- Search
- Languages and translations
- Images and rich text
- Tags, layouts, migrations and the website sidebar
- Mutations
- Uploads
- Drafts and preview tokens
- Subscriptions
- Persisted queries
- Introspection, the schema hash and code generation
- Errors
- Limits
- The complete core schema
End points and HTTP
| End point | Method | Use |
|---|---|---|
/api/graphql | POST, GET | queries and mutations (mutations: POST only) |
/api/graphql/subscribe | POST, GET | subscriptions as Server-Sent Events (graphql-sse); WebSocket through Velocity |
/api/graphql/playground | GET | redirects to the playground of the administration (/graphql/playground) |
/graphql/query | POST | the session end point: the signed-in browser session of the administration (policy graphql/query; mutations need the header X-CSRF-Token) |
The end point exists in every siteaccess where the API is switched on. A siteaccess is chosen like every other REST
request: by the host or the path prefix of the request, or by the header X-Siteaccess: <name> when that siteaccess
exists (an unknown name is ignored and the host decides).
The body of a request may be:
Content-Type | Body |
|---|---|
application/json (or no type and a body starting with {) | {"query": "...", "variables": {...}, "operationName": "...", "extensions": {...}} |
application/graphql | the query text alone |
multipart/form-data with a field operations | the GraphQL multipart request (files) |
application/x-www-form-urlencoded | the fields query, variables (JSON text), operationName, id |
A GET sends the same fields in the query string: query, variables (JSON text), operationName, and id
for a persisted query. extensions (JSON text) carries Apollo's persistedQuery.sha256Hash. A mutation by GET is
refused.
Request headers the API reads:
| Header | Meaning |
|---|---|
Authorization: Bearer <token> | a personal API key (expk_...) or an OAuth token; none: the anonymous user. See Authentication. |
X-Siteaccess | the siteaccess to answer in |
Accept-Language | the language of error messages (de-DE,de;q=0.9), never of content |
If-None-Match | the ETag of an answer you have: 304 when it is still current |
X-CSRF-Token | the form token of a session (session end point, mutations) |
Last-Event-ID | the position to resume a subscription from |
Origin | a browser's origin: CORS headers when it is allowed (CORS) |
The answer
{
"data": { "node": { "name": "Recipes", "url": "https://www.example.com/recipes" } },
"extensions": { "requestId": "9ec7706373d6dfc4", "schemaHash": "19deb36636de" }
}data: what the query asked for. A field the user may not read, or that is not there, isnull(a list leaves it out).errors: present when something went wrong; see Errors.datamay be partial: fields without errors keep their values.extensions.requestId: the id of this request (alsoX-Request-Id). An answer served from the response cache has norequestIdin the body; the header still has one.extensions.schemaHash: the hash of the schema (alsoX-GraphQL-Schema).
Status codes:
| Status | When |
|---|---|
200 | every answer GraphQL produced, errors included |
304 | If-None-Match matched the current ETag |
400 | the request could not be read: the body is not a JSON object, variables or extensions is not a JSON object, a multipart request is malformed |
401 | a credential was sent and refused ({"error":"invalid_token"}, header WWW-Authenticate); no GraphQL ran |
404 | the API is switched off in this siteaccess (DISABLED), or subscriptions are off |
429 | over a rate limit (RATE_LIMITED, Retry-After), a subscription limit (SUBSCRIPTION_LIMIT), or a browser check of the request shield (header Request-Shield-Challenge) |
503 | the library webonyx/graphql-php is not installed |
Answer headers:
| Header | Meaning |
|---|---|
X-Request-Id | the request id |
X-GraphQL-Schema | the schema hash |
ETag | the answer's tag; weak (W/"...") for ad-hoc queries, strong for persisted queries |
Cache-Control | private, no-store for ad-hoc queries; public, max-age=0, must-revalidate (anonymous) or private, no-cache (signed in) for persisted queries |
X-GraphQL-Cache | HIT, MISS (persisted queries) or BYPASS (an ad-hoc query while the cache is on) |
X-Exponential-Cache-Tags | the purge tags of what a query showed (Cache tags); never on mutations |
X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset | the rate limit, what is left, seconds until the window ends |
Retry-After | seconds to wait, on a 429 |
Vary | Origin, Authorization on answers of persisted queries |
Your first query, three ways
The front page's name and its first page of children:
query FrontPage {
node(urlAlias: "") {
name
url
children(limit: 5) {
totalCount
nodes { name classIdentifier urlAlias }
pageInfo { hasNextPage endCursor }
}
}
}curl
EXP=https://www.example.com
curl -s "$EXP/api/graphql" -H 'Content-Type: application/json' \
-d '{"query":"query FrontPage { node(urlAlias: \"\") { name url children(limit: 5) { totalCount nodes { name classIdentifier urlAlias } pageInfo { hasNextPage endCursor } } } }"}'fetch (Node.js 20+, Deno, Bun, browsers)
const query = `query FrontPage {
node(urlAlias: "") {
name url
children(limit: 5) { totalCount nodes { name classIdentifier urlAlias } pageInfo { hasNextPage endCursor } }
}
}`;
const res = await fetch('https://www.example.com/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
});
if (!res.ok && res.status !== 200) throw new Error(`HTTP ${res.status}`);
const { data, errors } = await res.json();
if (errors) throw new Error(errors.map((e) => `${e.extensions?.code}: ${e.message}`).join('\n'));
console.log(data.node.children.totalCount, res.headers.get('X-Exponential-Cache-Tags'));SDK
import { createClient, gql } from '@exponentialcms/client';
const client = createClient({ url: 'https://www.example.com', siteaccess: 'site' });
const FrontPage = gql<{
node: { name: string; url: string | null; children: { totalCount: number; nodes: { name: string; classIdentifier: string; urlAlias: string | null }[] } } | null;
}>`
query FrontPage {
node(urlAlias: "") { name url children(limit: 5) { totalCount nodes { name classIdentifier urlAlias } } }
}
`;
const result = await client.execute(FrontPage);
console.log(result.data.node?.children.totalCount, result.cacheTags, result.schemaHash, result.requestId);Variables, operation names, aliases and fragments
The API follows the GraphQL specification: variables, several operations in one document with operationName,
aliases (two node fields in one query), fragments and inline fragments, and the directives @include and @skip.
query TwoPages($a: String!, $b: String!, $withChildren: Boolean = false) {
first: node(urlAlias: $a) { ...Card children(limit: 3) @include(if: $withChildren) { nodes { name } } }
second: node(urlAlias: $b) { ...Card }
}
fragment Card on Content { id name url classIdentifier }curl -s "$EXP/api/graphql" -H 'Content-Type: application/json' -d '{
"query": "query TwoPages($a: String!, $b: String!, $withChildren: Boolean = false) { first: node(urlAlias: $a) { ...Card children(limit: 3) @include(if: $withChildren) { nodes { name } } } second: node(urlAlias: $b) { ...Card } } fragment Card on Content { id name url classIdentifier }",
"variables": {"a": "recipes", "b": "fitness", "withChildren": true},
"operationName": "TwoPages"
}'A document with several operations needs operationName, or the answer is an error (BAD_USER_INPUT, "The request
names no operation of the document."). The complexity of a query is computed with the values of its variables: a
limit: $n counts as $n.
Root queries
| Field | Arguments | Returns | Notes |
|---|---|---|---|
node | exactly one of id: Int, remoteId: String, path: String, urlAlias: String; language: String | Content | the content at a location. id is a node id; remoteId the location's remote id; path the path string /1/2/58/; urlAlias the URL alias in this siteaccess ("" the front page). null when there is none or the user may not read it. |
content | exactly one of id: Int, remoteId: String; version: Int (with id only); language: String | Content | a content object at its main location. id is an object id. With version: that version (a draft) for a user who may read it (content/versionread, or the user's own draft). |
preview | token: String! | Content | the version a preview token names, until it expires; no sign-in needed |
children | parentId: Int!, classes, sortField, sortOrder, depth = 1, limit, offset, first, after, language | ContentConnection! | the content below a location the user may read; see Lists |
search | text, classes, subtree: [Int!], sections: [Int!], publishedAfter, publishedBefore, facets: [String!], limit, offset, first, after, language | SearchResult! | see Search |
currentUser | User! | the user the request runs as: id, login, name, anonymous, signedInBy (anonymous, token, apikey, session, console) | |
siteaccess | SiteAccess! | name, languages (prioritized), rootNodeId, schemaHash | |
translations | [Language!]! | every content language of the installation: code, name | |
contentClasses | identifiers: [String!] | [ContentClass!]! | the classes of the schema for code generators; allowed only where introspection is (INTROSPECTION_DISABLED otherwise) |
tag | exactly one of id, remoteId, path (keywords from the top, food/pasta); language | Tag | eztags, while the extension is active |
tags | parentId = 0, keyword, limit, offset, language | [Tag!]! | eztags: the tags below a tag, or every tag with a keyword |
layout | exactly one of id, identifier, urlAlias | Layout | Exponential Layouts (explayouts): a published layout, or the layout its rules give a page |
migrationStatus, migrations, migrationRuns, migrationRun | see below | the migrations, for users with migration/read | |
expwtRead | action: String!, input: String | ExpwtAnswer! | a reading action of the website sidebar (expwt) |
A root query that gets the wrong combination of arguments answers BAD_USER_INPUT with a message that names the
rule, for example node needs exactly one of id, remoteId, path and urlAlias.
node versus content. node(id:) takes a node id and reads the content as reached by that location (its
url, parent and children are those of that location). content(id:) takes an object id and reads it at its main
location. On the media site, the front page is object 87 at node 89:
{
byNode: node(id: 89) { id name location { id } }
byObject: content(id: 87) { id name location { id } }
}Both answer {"id": 87, "name": "Fit & Healthy", "location": {"id": 89}}.
The Content interface and the class types
Every content class the schema shows is an object type that implements the interface Content. A query on node,
content, children or search returns Content; the fields of a particular class are read with an inline fragment
on its type:
{
node(urlAlias: "recipes/power-up-smoothie") {
name
... on ng_recipe {
title
image { url(alias: "medium") width(alias: "medium") height(alias: "medium") alt }
}
}
}The fields every content has (Content):
| Field | Type | Meaning |
|---|---|---|
id | Int! | the content object id |
remoteId | String! | the object's remote id |
name | String! | the name in the translation read |
classIdentifier | String! | the class identifier (ng_article) |
className | String! | the class name |
published, modified | String | ISO 8601 with the server's time zone offset (2023-01-25T09:51:01-08:00) |
language | String! | the translation the fields are read in |
languages | [String!]! | its translations |
mainLanguage | String! | the language it was first written in |
ownerId, ownerName | Int, String | the owner's object id and name |
sectionId | Int | its section |
url | String | the absolute address of the location it was reached by, in this siteaccess |
urlAlias | String | the URL alias of that location (about/company; "" for the front page) |
location | Location | the location it was reached by (the node a query or list named, else the main one) |
mainLocation | Location | the main location |
locations | [Location!]! | every location the user may read |
parent | Content | the content of the parent of the location it was reached by |
children(...) | ContentConnection! | the content below that location (same arguments as the root children, without parentId and language) |
Field names. With NamingStyle=identifier (the default) a class ng_article is the type ng_article and its
attribute teaser_title the field teaser_title. NamingStyle=pascal gives NgArticle and teaserTitle;
NamingStyle=map takes the names of [GraphQLNaming] TypeNames[] and FieldNames[]. A name that is not a valid
GraphQL name has every invalid character replaced by _ (and a _ in front when it starts with a digit). An attribute
named like a field every content has (name, id, children ...) gets the suffix _field: the attribute name
is name_field. A class whose type name would be a name the kernel uses (Image, Tag, Location ...) gets the
suffix Content (ImageContent). Changing the naming style changes the schema hash and breaks every query that used
the old names: decide it once, before the first client.
What the schema shows. ClassList[] (empty: every class) minus ExcludedClassList[] (user, user_group,
common_ini_settings, template_look by default); without the attributes of HiddenFieldList[]
(<class>/<attribute> or */<attribute>) and of the datatypes of HiddenDatatypeList[] (ezuser, ezpassword).
Content of a class the schema does not show is never returned, not even as Content.
The Location type
| Field | Type | Meaning |
|---|---|---|
id | Int! | the node id |
remoteId | String | the location's remote id |
parentId | Int | the parent's node id |
depth | Int! | the depth in the tree (the root is 1) |
pathString | String! | /1/2/58/ |
priority | Int | its priority among its siblings |
hidden | Boolean! | hidden itself |
invisible | Boolean! | hidden, or below a hidden location |
urlAlias, url | String | as on Content |
content | Content | the content at the location |
parent | Content | the content of the parent location |
children(...) | ContentConnection! | the content below |
layout | Layout | the layout the rules of Exponential Layouts give this page (when explayouts is active) |
Lists and pagination
children, Content.children, Location.children, Tag.content and search return a connection:
type ContentConnection { totalCount: Int! nodes: [Content!]! edges: [ContentEdge!]! pageInfo: PageInfo! }
type ContentEdge { cursor: String! node: Content! }
type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String }totalCountis one count query: how many items the user may read in all.nodesandedgesare the same items; ask foredgesonly when you need the cursors.- Without
limitorfirsta list returnsDefaultListLimititems (25). A largerlimitorfirstthanMaxListLimit(100) is lowered to it, silently.
Offset pagination: limit and offset. Page 3 of 10:
{ children(parentId: 2, depth: 4, classes: ["ng_article"], limit: 10, offset: 20, sortField: PUBLISHED, sortOrder: DESC) {
totalCount nodes { name url published } } }Cursor pagination: first and after. A cursor is the position of an item in the whole list
(base64("exp:<position>"), e.g. ZXhwOjQ=); after a cursor the list continues with the next position. Treat
cursors as opaque: a cursor this API did not give answers BAD_USER_INPUT ("The cursor of after is not one this API
gave.").
query Articles($after: String) {
children(parentId: 2, depth: 4, classes: ["ng_article"], first: 50, after: $after, sortField: PUBLISHED, sortOrder: DESC) {
totalCount
edges { cursor node { id name url } }
pageInfo { hasNextPage endCursor }
}
}A complete walk over all items with the SDK:
let after: string | null = null;
const all: { id: number; name: string }[] = [];
do {
const { children } = await client.request<{ children: { nodes: { id: number; name: string }[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } } }>(
`query Walk($after: String) { children(parentId: 2, depth: 10, first: 100, after: $after, sortField: NODE_ID) {
nodes { id name } pageInfo { hasNextPage endCursor } } }`,
{ after },
);
all.push(...children.nodes);
after = children.pageInfo.hasNextPage ? children.pageInfo.endCursor : null;
} while (after);Stable walks. Positions are offsets into the list as it is at the moment of each request. Content published or
removed during a walk shifts later positions: an item can be seen twice or missed. For a complete export sort by
NODE_ID (new content gets higher node ids and lands at the end), de-duplicate by id, and repeat changes that
arrive by webhook meanwhile.
Complexity of lists. A list field counts its limit (or first) times the fields below it, plus one. Nested lists
multiply: children(limit: 100) { nodes { children(limit: 100) { nodes { name } } } } has a complexity of 20201 and is
refused (COMPLEXITY_LIMIT, at most 1000 by default). Fetch the second level in a separate request, lower the
limits, or raise MaxComplexity for a signed-in siteaccess.
Filtering and sorting
| Argument | Type | Meaning |
|---|---|---|
classes | [String!] | only content of these class identifiers; an identifier the schema does not show matches nothing |
depth | Int = 1 | how deep below the location: 1 the children, 2 children and grandchildren, a large number the whole subtree |
sortField | ContentSortField | PATH, PUBLISHED, MODIFIED, SECTION, DEPTH, CLASS_IDENTIFIER, CLASS_NAME, PRIORITY, NAME, NODE_ID |
sortOrder | SortOrder | ASC (the default) or DESC, with sortField |
language | String | the translation the items are read in (root children only) |
Without sortField a list is sorted as the parent location is sorted in the administration (its "sort by" setting).
Hidden and invisible content follows the policies and the siteaccess's visibility settings, as on the classic site.
For filters beyond classes and the tree (sections, dates, text), use search. For content tagged with a tag,
use Tag.content. Filtering by an attribute's value is not offered by the list fields; select the attribute and filter
in your code, or index the content with Solr (ezfind) and use search(text:) with the engine's syntax.
Search
query Search($q: String!, $after: String) {
search(text: $q, classes: ["ng_article", "ng_recipe"], subtree: [89], first: 10, after: $after) {
totalCount
engine
nodes { name url classIdentifier ... on ng_article { teaser_title } }
pageInfo { hasNextPage endCursor }
}
}| Argument | Meaning |
|---|---|
text | the words, in the syntax of the installation's search engine |
classes | class identifiers |
subtree | only content below these node ids |
sections | only these section ids |
publishedAfter, publishedBefore | dates; ISO 8601 (2026-10-30) is the format to use. Any text PHP's strtotime() reads is accepted; another answers BAD_USER_INPUT. |
facets | facets to count (class, section, author, keywords, year ...), with an engine that has them |
limit, offset, first, after | as for lists |
language | only content in this language (the engine's language filter) and read in it |
- A search needs
textor at least one filter; otherwiseBAD_USER_INPUT("search needs a text or a filter ..."). SearchResulthastotalCount(what the user may read),nodes,edges,pageInfo,engine(eZSearchEngineoreZSolr) andfacets([SearchFacet!]!:field,values { value name count }). With the kernel's own enginefacetsis empty.- Results are best match first. The answer of a search carries the cache tag
dq; every publish purges it.
Languages and translations
siteaccess { languages }is the siteaccess's prioritized language list;translationslists every language of the installation.- Without
language, content is read in the first language of the siteaccess's list it has. - With
language(onnode,content,children,search,ContentEvent.content), the content is read in that translation where it has one; otherwise in the translation it would have been read in without the argument.Content.languagealways says which translation you got. - Lists are not filtered by language (
children(language: "ger-DE")still lists items that have no German translation). Filter bylanguagesin your code, or usesearch(language:), which only finds content in that language. urlandurlAliasare the addresses in the siteaccess that answers. For the German addresses of a German siteaccess, ask that siteaccess (X-Siteaccess: <german siteaccess>).
{
en: node(urlAlias: "about") { name language languages url }
de: node(urlAlias: "about", language: "ger-DE") { name language }
}Error messages follow Accept-Language (or the siteaccess's locale); content never does.
Images and rich text
Short form; the complete shapes are on Datatypes in GraphQL.
{
node(urlAlias: "recipes/power-up-smoothie") {
... on ng_recipe {
image {
url(alias: "medium") width(alias: "medium") height(alias: "medium") mimeType(alias: "medium") alt
variations(aliases: ["small", "large"]) { alias url width height }
}
}
}
}url(alias:)takes any alias ofimage.ini;"original"is the default. An alias that does not exist answersBAD_USER_INPUT("There is no image alias ...").variationswithoutaliaseslistsImageAliasList[](small,medium,large).- An alias is made when it is first asked for. Its address may be a signed address of the form
/content/image/<payload>.<signature>/<file name>: use it as it is; never build image addresses yourself. RichTexthashtml(rendered as the site renders it),text(plain),xml(stored) andexcerpt(length: 200)(plain text cut at a word).
Tags, layouts, migrations and the website sidebar
These root queries come from schema extensions that the kernel ships and that answer only where their extension is
active (graphql.ini SchemaExtensionList[]).
Tags (eztags). tag(id | remoteId | path, language), tags(parentId, keyword, limit, offset, language). A
Tag has id, keyword, remoteId, parentId, mainTagId, isSynonym, depth, pathString, modified,
languages, url, parent, mainTag, path, children(limit, offset), childrenCount, synonyms, and
content(...): the content tagged with it or a synonym, below the root of the siteaccess (a connection; depth is
ignored). Fields of the datatype eztags are [Tag!]!.
{ tag(path: "food/pasta") { keyword synonyms { keyword } content(first: 10, classes: ["ng_recipe"]) { totalCount nodes { name url } } } }Layouts (Exponential Layouts). layout(id | identifier | urlAlias) and Location.layout: the published layout,
its zones (identifier, linkedLayoutId, linkedZone, blocks), zone(identifier:), and each block's
definition, viewType, itemViewType, name, position, placeholder, parameters { name value },
parameter(name:), collectionType (manual, dynamic or null), items (the content placed by hand) and
children (blocks in a container). A zone linked to a zone of a shared layout shows that zone's blocks.
{ layout(urlAlias: "") { name zones { identifier blocks { definition viewType items { name url } } } } }Migrations (policy migration/read; null or an empty list without it): migrationStatus (pending, failed,
orphans, total, ready, environment, engine, lock, warnings, errors), migrations(state, source),
migrationRuns(limit = 20, offset = 0), migrationRun(id:).
The website sidebar (expwt). expwtRead(action, input) and the mutation expwtWrite(action, input) run the
actions of the editing sidebar; the input and the data are JSON text. They exist for that sidebar and are listed here
for completeness.
Mutations
Mutations change content with the user's rights, through the same kernel operations as the administration: the
workflows of content/publish, content/move and the others run, every mutation is recorded in the audit
(content.graphql.mutation; a refusal or an error as content.graphql.mutation.failed), and the response cache is
expired.
Who may send one (checked before anything runs, in this order):
| Rule | Refusal |
|---|---|
mutations are on in the siteaccess (MutationsEnabled=enabled, the default) | DISABLED "Mutations are switched off in this siteaccess ..." |
the request is a POST | BAD_USER_INPUT "Send a mutation with POST." |
the request is signed in (or AnonymousMutations=enabled, or every root field is one a schema extension opens to anonymous callers) | FORBIDDEN "Sign in to change content." |
a personal API key has the scope graphql:write | FORBIDDEN "The API key has no scope graphql:write." |
a session sent its form token (X-CSRF-Token) | FORBIDDEN "A mutation with a session needs the form token ..." |
Then each mutation checks the user's policies on the content it changes; a refusal is FORBIDDEN "You may not do this
to this content.", content that is not there or not readable is NOT_FOUND.
The answer of every content mutation is ContentPayload:
| Field | Meaning |
|---|---|
status | PUBLISHED, DRAFT (with publish: false), PENDING (a workflow holds it, an approval), CANCELLED (a workflow cancelled it; nothing changed), DONE (moved, hidden, revealed, a location added, a section or state set), TRASHED, DELETED |
contentId | the object id |
nodeId | the location changed or made (the main location of new content) |
version | the version written |
content | the content now, as the user may read it (a draft: that version); null when it is gone or held by a workflow |
The mutations
| Mutation | Arguments | Policies |
|---|---|---|
createContent | parentId: Int!, classIdentifier: String!, fields: [FieldInput!]!, language, remoteId, publish = true | content/create of the class below the parent, in the language |
updateContent | id: Int!, fields: [FieldInput!]!, language, publish = true | content/edit |
translateContent | id: Int!, language: String!, fields: [FieldInput!], publish = true | content/edit in the new language (a role limited to languages must include it) |
publishDraft | id: Int!, version: Int! | the user's own draft, or one the user may read and edit |
deleteContent | exactly one of id: Int (every location) and nodeId: Int (one); trash = true | content/remove |
moveContent | nodeId: Int!, newParentId: Int! | content/edit and content/remove here, content/create there |
hideContent / revealContent | nodeId: Int! | content/hide |
addLocation | id: Int!, parentId: Int! | content/edit of the object, content/create below the new parent |
assignSection | nodeId: Int!, sectionId: Int!, scope = "subtree" (subtree or object) | section/assign of that section to that content; with subtree, objects below that the user may not assign keep their section |
setObjectStates | id: Int!, states: [String!]! (group/state by identifier, review/approved) | state/assign for every state; refused as a whole when one is unknown (BAD_USER_INPUT) or not allowed (FORBIDDEN); the kernel's own groups (ez...) cannot be set here |
restoreContent | id: Int!, parentId: Int | content/restore and content/create below the parent (the original one by default) |
uploadImage | file: Upload!, parentId: Int!, name, alt, classIdentifier = "image", fieldIdentifier = "image", nameIdentifier = "name", language, publish = true | as createContent |
uploadFromUrl | url: String! and the arguments of uploadImage without file | as createContent; only hosts of UploadFromUrlHostList[] |
createPreviewToken | id: Int!, version, language, ttl | reading that version |
Fields to write are a list of FieldInput:
input FieldInput {
identifier: String! # the attribute identifier (title, image)
value: String # the value in the string format of the datatype
format: FieldFormat = RAW # rich text only: TEXT or HTML
upload: Upload # a file of the request, for file fields
}The value is the datatype's string format, the format of the kernel's CSV import (an integer "42", a boolean
"1", a date as a Unix timestamp, a relation list as "57-58-59" ...). Every datatype's format is in
Datatypes in GraphQL, "Writing". Rich text takes the stored XML (RAW), plain text
(TEXT: a paragraph per block separated by a blank line), or simple HTML (HTML: p, h1-h6, strong, em, a,
ul, ol, li, table ...). File fields (ezimage, ezbinaryfile, ezmedia, and FileDatatypeList[]) take
upload, never a value.
Checks before anything is written (BAD_USER_INPUT): the attribute must be in the schema ("The class ... has no
field ... that may be written."), given once, a file field needs an upload and other fields no upload, format only
on rich text, and a new object needs every required attribute ("The field ... is required.").
Examples
Create and publish an article (a key with graphql:write):
KEY=expk_xxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
curl -s "$EXP/api/graphql" -H 'Content-Type: application/json' -H "Authorization: Bearer $KEY" -d '{
"query": "mutation Create($parent: Int!, $fields: [FieldInput!]!) { createContent(parentId: $parent, classIdentifier: \"ng_article\", fields: $fields) { status contentId nodeId version content { url } } }",
"variables": {
"parent": 92,
"fields": [
{"identifier": "title", "value": "Ten minutes a day"},
{"identifier": "full_intro", "value": "Short sessions, every day.", "format": "TEXT"},
{"identifier": "body", "value": "<p>Start <strong>small</strong>.</p><ul><li>Walk</li><li>Stretch</li></ul>", "format": "HTML"}
]
}
}'import { apiKey, createClient } from '@exponentialcms/client';
const writer = createClient({ url: 'https://www.example.com', auth: apiKey(process.env.EXPONENTIAL_WRITE_KEY!) });
const { createContent } = await writer.request<{ createContent: { status: string; contentId: number; nodeId: number } }>(
`mutation Create($parent: Int!, $fields: [FieldInput!]!) {
createContent(parentId: $parent, classIdentifier: "ng_article", fields: $fields) { status contentId nodeId }
}`,
{ parent: 92, fields: [{ identifier: 'title', value: 'Ten minutes a day' }] },
);Update one field and leave the new version a draft, then publish it:
mutation { updateContent(id: 1504, fields: [{ identifier: "title", value: "Power-up Smoothie (new)" }], publish: false) { status version } }
mutation { publishDraft(id: 1504, version: 3) { status content { name } } }Translate, move, hide, place twice, section, states, trash and restore:
mutation { translateContent(id: 1504, language: "ger-DE", fields: [{ identifier: "title", value: "Power-Smoothie" }]) { status content { language name } } }
mutation { moveContent(nodeId: 1520, newParentId: 144) { status nodeId } }
mutation { hideContent(nodeId: 1520) { status } }
mutation { revealContent(nodeId: 1520) { status } }
mutation { addLocation(id: 1504, parentId: 92) { status nodeId } }
mutation { assignSection(nodeId: 1520, sectionId: 3, scope: "object") { status } }
mutation { setObjectStates(id: 1504, states: ["review/approved"]) { status } }
mutation { deleteContent(nodeId: 1520) { status } }
mutation { restoreContent(id: 1504) { status nodeId } }Several mutations in one document run one after the other, in the order written; one that fails does not undo the others (each is its own transaction). Send one mutation per request when the outcome of each matters.
Workflows. When a workflow holds a publish (an approval), the answer is PENDING and content is null; the
content is published when the workflow goes on, and a publish event follows then. CANCELLED means a workflow
stopped it and nothing changed.
Idempotency. Mutations are not idempotent: a retried createContent makes a second object. Give new content a
remoteId you derive from your source (remoteId: "shop-product-4711"): a second create with the same remote id is
refused (BAD_USER_INPUT "The remote id ... is taken."), so a retry cannot duplicate. The SDK never retries a
mutation unless you set retryMutations: true.
Uploads
Files travel in a multipart request following the GraphQL multipart request specification: a field operations (the
JSON request with null where the file goes), a field map (which form field fills which variable), and the files.
curl -s "$EXP/api/graphql" -H "Authorization: Bearer $KEY" \
-F operations='{"query":"mutation($file: Upload!) { uploadImage(file: $file, parentId: 51, alt: \"A green smoothie\") { status contentId nodeId content { ... on image { image { url(alias: \"medium\") } } } } }","variables":{"file":null}}' \
-F map='{"0":["variables.file"]}' \
-F 0[email protected]A file for a field of createContent or updateContent goes into FieldInput.upload:
curl -s "$EXP/api/graphql" -H "Authorization: Bearer $KEY" \
-F operations='{"query":"mutation($f: [FieldInput!]!) { createContent(parentId: 51, classIdentifier: \"file\", fields: $f) { status contentId } }","variables":{"f":[{"identifier":"name","value":"Price list"},{"identifier":"file","upload":null}]}}' \
-F map='{"0":["variables.f.1.upload"]}' \
-F 0[email protected]With the SDK, put a Blob or File into the variables; the client sends a multipart request by itself:
const file = new Blob([await fs.promises.readFile('smoothie.jpg')], { type: 'image/jpeg' });
await writer.request(
`mutation($file: Upload!) { uploadImage(file: $file, parentId: 51) { status contentId } }`,
{ file },
);- At most
MaxUploadSizebytes (32 MB by default; PHP'supload_max_filesizeandpost_max_sizeapply first). - Every file passes the checks of
UploadCheckList[](classes implementingexpGraphQLUploadCheck: a virus scanner, a type filter); the first that gives a reason refuses it. uploadFromUrl(url:)fetches anhttpsaddress of a host inUploadFromUrlHostList[](no redirects, at mostMaxUploadSize); with the list empty (the default) it is off.
Upload errors (BAD_USER_INPUT): "The file ... is larger than ... bytes.", "The file ... did not arrive whole (upload
error ...).", "The multipart request has no file ...", "The field map of a multipart request is not a JSON object.",
"A variable of type Upload takes a file of a multipart request.", "The file could not be fetched." (uploadFromUrl).
Drafts and preview tokens
A front end shows an editor a draft before it is published:
The editor's client (or your server, with a key of a user who may read the draft) asks for a token:
mutation { createPreviewToken(id: 1504, version: 3, language: "eng-US", ttl: 1800) { token expires contentId version language } }Without
versionthe token names the user's newest draft, else the published version.ttldefaults toPreviewTokenTtl(3600 s) and is capped atMaxPreviewTokenTtl(86400 s).Anyone with the token reads that version, without signing in, until it expires:
query Preview($token: String!) { preview(token: $token) { name language ... on ng_article { title body { html } } } }
A token looks like exp1.<base64url payload>.<base64url HMAC>; it names the object, version, language, the user who
made it and the expiry, and is signed with the installation's secret key (EXP_SECRET_KEY or
var/secrets/exp_secret.key). Rotating that key ends every token. An invalid or expired token answers
FORBIDDEN ("The preview token is not valid or has expired."). The SDK's createPreviewHandler keeps the token in an
HttpOnly cookie; see the cookbook recipe Draft preview.
Subscriptions
subscription { contentPublished(classes: ["ng_article"], subtreeId: 89) { id event objectId time content { name url } } }Root fields: contentEvents(events, classes, parentId, subtreeId), contentPublished, contentUpdated,
contentDeleted, contentMoved, contentHidden (each with classes, parentId, subtreeId). They are sent to
/api/graphql/subscribe, never to /api/graphql ("Send subscriptions to /api/graphql/subscribe ..."). One
subscription asks for exactly one root field. The transports, the event fields, the limits and resuming are on
Events, webhooks and subscriptions.
Persisted queries
A persisted query is stored on the server and called by its name or its SHA-256. It is the only kind of query the
response cache keeps, and the fastest: an anonymous GET of a cached one is answered before the kernel starts.
Storing (on the server, in your deployment):
./console exp:graphql:persist queries/ # check every .graphql file against the schema, store nothing
./console exp:graphql:persist queries/ --apply # store each under its SHA-256 and its file name without .graphql
./console exp:graphql:persist menu.graphql --name=main-menu --apply
./console exp:graphql:persist --list
./console exp:graphql:persist --remove=main-menu --applyEach query is checked against the schema and the limits with the worst-case values of its variables (an Int as
MaxListLimit), so a stored query never fails a limit when it is called. An extension ships read-only queries in a
directory of PersistedQueryDirectoryList[] (<name>.graphql). The store is var/<site>/graphql/persisted/.
Calling by name with GET (variables as JSON in the query string):
curl -s -G "$EXP/api/graphql" --data-urlencode 'id=articles' --data-urlencode 'variables={"limit":10}'const url = new URL('https://www.example.com/api/graphql');
url.searchParams.set('id', 'articles');
url.searchParams.set('variables', JSON.stringify({ limit: 10 }));
const { data } = await (await fetch(url)).json();const result = await client.persisted('articles', { limit: 10 }); // GET; result.cacheState: HIT, MISS or BYPASSBy hash (Apollo): {"extensions":{"persistedQuery":{"version":1,"sha256Hash":"<sha256>"}}} in a JSON body or as
extensions= in the query string.
Automatic persisted queries. A client that sends the text together with its SHA-256 stores it, when it may
(AutomaticPersistedQueries: signed-in by default, enabled for everybody, disabled for the console only), up to
MaxPersistedQueries (1000). A query that may not be stored still runs, ad hoc.
| Setting | Values | Effect |
|---|---|---|
PersistedQueries | enabled (default), disabled | off: an id or hash answers PERSISTED_QUERY_NOT_SUPPORTED |
AutomaticPersistedQueries | signed-in (default), enabled, disabled | who may store by sending text and hash |
PersistedQueriesOnly | disabled (default), anonymous, enabled | only persisted queries at /api/graphql: for anonymous requests, or for all; an ad-hoc query answers PERSISTED_QUERY_REQUIRED. The session end point and the console always run anything. |
Errors: PERSISTED_QUERY_NOT_FOUND (message PersistedQueryNotFound, as Apollo Client expects: it then sends the
text), PERSISTED_QUERY_NOT_SUPPORTED (PersistedQueryNotSupported), BAD_USER_INPUT for a hash that is not a
SHA-256 or does not match the text.
Introspection, the schema hash and code generation
- Introspection (
__schema,__type) is allowed byIntrospection:signed-in(the default: a key, a token, a session),enabled(everybody) ordisabled(only the console). Refused:INTROSPECTION_DISABLED. contentClasses(identifiers:)lists the classes of the schema with each field'sidentifier,fieldName,datatype,graphqlType,mapped(the datatype has a mapping of its own),required,translatable,searchableandoptions(selection options): what@exponentialcms/codegenreads. Allowed where introspection is.- The schema hash (12 hexadecimal characters) changes when a class, an attribute, the naming, the settings that
shape the schema or the schema extensions change. Generate your types for one hash and check
X-GraphQL-Schemain your build. - The console prints the schema without the API being on:
./console exp:graphql:schema --siteaccess=site(--format=sdldefault,jsonthe introspection result,summarythe classes and the datatypes that fall back toString),--output=schema.graphql.
# the SDL for your code generator, from a signed-in request
curl -s "$EXP/api/graphql" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
-d '{"query":"{ contentClasses(identifiers: [\"ng_article\"]) { identifier typeName fields { identifier fieldName datatype graphqlType required } } }"}'Errors
An error follows the GraphQL specification, with extensions.code and extensions.requestId:
{
"errors": [
{
"message": "node needs exactly one of id, remoteId, path and urlAlias.",
"locations": [ { "line": 1, "column": 3 } ],
"path": [ "node" ],
"extensions": { "code": "BAD_USER_INPUT", "requestId": "029c3f6310f931ef" }
}
],
"data": { "node": null },
"extensions": { "requestId": "029c3f6310f931ef", "schemaHash": "19deb36636de" }
}The codes. A code, once released, keeps its name and meaning; new codes are only added. Decide by the code; show the message.
extensions.code | HTTP | Meaning | What to do |
|---|---|---|---|
PARSE | 200 | not valid GraphQL syntax | fix the query (the message names line and column) |
VALIDATION | 200 | does not fit the schema: an unknown field, a wrong argument type, a missing fragment | check the schema; the class or attribute may be hidden, or the naming style differs |
BAD_USER_INPUT | 200 (400 for an unreadable request) | an argument is wrong, or the request cannot be read | read the message; it names the argument |
DEPTH_LIMIT | 200 | deeper than MaxDepth | flatten the query |
COMPLEXITY_LIMIT | 200 | more complex than MaxComplexity | lower limit/first, split nested lists |
INTROSPECTION_DISABLED | 200 | this request may not read the schema | sign in, or use the console |
DISABLED | 404 (200 for mutations) | the API is off in this siteaccess, mutations or subscriptions are off | switch it on, or use the right siteaccess |
FORBIDDEN | 200 (403 at /api/graphql/subscribe) | a mutation the request may not send, a change the policies do not allow, an invalid preview token, a subscription without sign-in | sign in, give the key graphql:write, give the role the policy |
NOT_FOUND | 200 | a mutation on content that is not there or not readable (a query answers null instead) | check the id and the user's read rights |
INTERNAL | 200 (503 without the library) | an error in the code | quote the request id; the server log has the details |
PERSISTED_QUERY_NOT_FOUND | 200 | no persisted query has this id or hash | store it, or send the text |
PERSISTED_QUERY_NOT_SUPPORTED | 200 | persisted queries are off | send the text |
PERSISTED_QUERY_REQUIRED | 200 | an ad-hoc query where only persisted queries are accepted | persist the query and send its id |
RATE_LIMITED | 429 | over the rate limit | wait Retry-After seconds |
SUBSCRIPTION_LIMIT | 429 | too many open subscriptions | close one; try later |
Messages you will meet, with their code:
| Message | Code |
|---|---|
| The GraphQL API is switched off in this siteaccess. | DISABLED |
| The GraphQL library is not installed. | INTERNAL (503) |
| The request has no query. | BAD_USER_INPUT |
| The query is longer than … bytes. | BAD_USER_INPUT |
| The query is … levels deep; at most … are allowed. | DEPTH_LIMIT |
| The query has a complexity of …; at most … is allowed. | COMPLEXITY_LIMIT |
| This request may not read the schema (introspection). | INTROSPECTION_DISABLED |
| node needs exactly one of id, remoteId, path and urlAlias. | BAD_USER_INPUT |
| content needs exactly one of id and remoteId. / content takes version with id only. | BAD_USER_INPUT |
| tag needs exactly one of id, remoteId and path. / layout needs exactly one of id, identifier and urlAlias. | BAD_USER_INPUT |
| search needs a text or a filter (classes, subtree, sections, publishedAfter, publishedBefore). | BAD_USER_INPUT |
| … is not a date (ISO 8601, 2026-10-30). | BAD_USER_INPUT |
| The cursor of after is not one this API gave. | BAD_USER_INPUT |
| There is no image alias … (image.ini [AliasSettings] AliasList[]). | BAD_USER_INPUT |
| Send subscriptions to /api/graphql/subscribe (an event stream or a WebSocket). | BAD_USER_INPUT |
| Send a mutation with POST. | BAD_USER_INPUT |
| Sign in to change content. | FORBIDDEN |
| The API key has no scope graphql:write. | FORBIDDEN |
| A mutation with a session needs the form token of the session (header X-CSRF-Token). | FORBIDDEN |
| You may not do this to this content. | FORBIDDEN |
| The content is not there, or you may not read it. | NOT_FOUND |
| The class … has no field … that may be written. / The field … is given twice. / The field … is required. / The field … needs a value. | BAD_USER_INPUT |
| The field … takes a file: send it as upload (a multipart request). / The field … takes no file. | BAD_USER_INPUT |
| The format … is only for rich text fields; … takes its value as it is (RAW). / The HTML could not be read. | BAD_USER_INPUT |
| The value of the field … could not be stored. | BAD_USER_INPUT |
| There is no content class … in the schema. / There is no content language …. | BAD_USER_INPUT |
| The remote id … is taken. | BAD_USER_INPUT |
| deleteContent needs exactly one of id and nodeId. / Give at least one field. | BAD_USER_INPUT |
| Version … is not a draft. / No new version could be made (the content has too many drafts). | BAD_USER_INPUT |
| The content has a translation in … already: use updateContent. | BAD_USER_INPUT |
| The content has a location below … already. / A location cannot be moved below itself. | BAD_USER_INPUT |
| scope is subtree or object. / There is no such section. | BAD_USER_INPUT |
| states names at least one group/state. / There is no object state …. | BAD_USER_INPUT |
| The original location is gone: name the parentId to restore it below. | BAD_USER_INPUT |
| The preview token is not valid or has expired. | FORBIDDEN |
| Too many requests: at most … in … seconds. Try again in … seconds. | RATE_LIMITED |
| Internal server error | INTERNAL |
The language of messages. A message is written in the language of Accept-Language (the first language that has
an administration translation), else in the siteaccess's locale. Validation and syntax messages of the GraphQL
specification stay in English, and PersistedQueryNotFound/PersistedQueryNotSupported stay as they are.
curl -s "$EXP/api/graphql" -H 'Accept-Language: de' -H 'Content-Type: application/json' \
-d '{"query":"{ node(id: 1, urlAlias: \"x\") { id } }"}'
# {"errors":[{"message":"node braucht genau eines von id, remoteId, path und urlAlias.", ... "code":"BAD_USER_INPUT" ...Debug. Debug=enabled adds the PHP exception and its trace to extensions.debug and disables the response cache.
Only on a development siteaccess: a trace tells paths and code to whoever asks.
Handling errors with the SDK:
import { ExponentialGraphQLError, ExponentialRateLimitError, ExponentialShieldChallengeError, ExponentialHttpError } from '@exponentialcms/client';
try {
await client.request(query, variables);
} catch (error) {
if (error instanceof ExponentialGraphQLError) {
if (error.hasCode('NOT_FOUND')) return notFound();
console.error(error.codes, error.message); // codes: the extensions.code of every error
} else if (error instanceof ExponentialRateLimitError) {
await new Promise((r) => setTimeout(r, error.retryAfterMs ?? 1000));
} else if (error instanceof ExponentialShieldChallengeError) {
// the request shield wants a browser check: exempt /api/** for programs, or send a key
} else if (error instanceof ExponentialHttpError) {
console.error(error.status); // 401, 404, 503 ...
}
throw error;
}Pass allowPartial: true to get data and errors together instead of an exception.
Limits
| Setting | Default | Error |
|---|---|---|
MaxQueryLength | 100000 bytes | BAD_USER_INPUT |
MaxDepth | 12 | DEPTH_LIMIT |
MaxComplexity | 1000 | COMPLEXITY_LIMIT |
MaxListLimit | 100 | (lowered silently) |
DefaultListLimit | 25 | |
RateLimit / RateLimitAnonymous / RateLimitPublicKey per RateLimitWindow | 600 / 120 / 3000 per 60 s | RATE_LIMITED |
MaxUploadSize | 32M | BAD_USER_INPUT |
MaxPersistedQueries | 1000 | (not stored; runs ad hoc) |
MaxSubscriptions, MaxSubscriptionsPerUser, MaxSubscriptionsPerAddress | 200, 5, 10 | SUBSCRIPTION_LIMIT |
| Purge tags per answer | 500 (more: only ez-all) |
All are in settings/graphql.ini [GraphQLSettings]; change them per siteaccess in
settings/siteaccess/<name>/graphql.ini.append.php or for every siteaccess in
settings/override/graphql.ini.append.php.
The complete core schema
The types every installation has (class types and the types of schema extensions come on top). Print your own with
./console exp:graphql:schema.
interface Content {
id: Int! remoteId: String! name: String! classIdentifier: String! className: String!
published: String modified: String language: String! languages: [String!]! mainLanguage: String!
ownerId: Int ownerName: String sectionId: Int url: String urlAlias: String
location: Location mainLocation: Location locations: [Location!]! parent: Content
children(classes: [String!], sortField: ContentSortField, sortOrder: SortOrder, depth: Int = 1,
limit: Int, offset: Int, first: Int, after: String): ContentConnection!
}
type Location {
id: Int! remoteId: String parentId: Int depth: Int! pathString: String! priority: Int
hidden: Boolean! invisible: Boolean! urlAlias: String url: String content: Content parent: Content
children(classes: [String!], sortField: ContentSortField, sortOrder: SortOrder, depth: Int = 1,
limit: Int, offset: Int, first: Int, after: String): ContentConnection!
layout: Layout
}
enum ContentSortField { PATH PUBLISHED MODIFIED SECTION DEPTH CLASS_IDENTIFIER CLASS_NAME PRIORITY NAME NODE_ID }
enum SortOrder { ASC DESC }
type ContentConnection { totalCount: Int! nodes: [Content!]! edges: [ContentEdge!]! pageInfo: PageInfo! }
type ContentEdge { cursor: String! node: Content! }
type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String }
type SearchResult { totalCount: Int! nodes: [Content!]! edges: [ContentEdge!]! pageInfo: PageInfo! engine: String! facets: [SearchFacet!]! }
type SearchFacet { field: String! values: [SearchFacetValue!]! }
type SearchFacetValue { value: String! name: String count: Int! }
type User { id: Int! login: String name: String anonymous: Boolean! signedInBy: String! }
type SiteAccess { name: String! languages: [String!]! rootNodeId: Int schemaHash: String! }
type Language { code: String! name: String }
type ContentClass { identifier: String! typeName: String! name: String! description: String! container: Boolean! fields: [ContentClassField!]! }
type ContentClassField { identifier: String! fieldName: String! name: String! description: String! datatype: String!
graphqlType: String mapped: Boolean! required: Boolean! translatable: Boolean! searchable: Boolean! options: [SelectionOption!]! }
input FieldInput { identifier: String! value: String format: FieldFormat = RAW upload: Upload }
enum FieldFormat { RAW TEXT HTML }
scalar Upload
type ContentPayload { status: MutationStatus! contentId: Int nodeId: Int version: Int content: Content }
enum MutationStatus { PUBLISHED DRAFT PENDING CANCELLED DONE TRASHED DELETED }
type PreviewToken { token: String! expires: String! contentId: Int! version: Int! language: String! }
enum ContentEventKind { publish update trash delete move hide reveal mutation clear }
type ContentEvent {
id: ID! event: ContentEventKind! time: String! objectId: Int remoteId: String version: Int
classIdentifier: String name: String language: String languages: [String!]! nodeIds: [Int!]!
mainNodeId: Int parentNodeIds: [Int!]! oldParentNodeId: Int newParentNodeId: Int
mutation: String migration: String objectIds: [Int!]! data: [ContentEventDatum!]!
content(language: String): Content
}
type ContentEventDatum { name: String! value: String values: [String!] }The value types of the datatypes (Image, RichText, Price ...) are listed on Datatypes in GraphQL.