Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,212 of 9,212 pages
About the help in other languages
All help pages

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…

Download as PDF

Address: https://doc.exponential.earth/learninminutes/exphelp/viewer/headless/graphql-reference.md

On this page

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

  1. End points and HTTP
  2. The answer
  3. Your first query, three ways
  4. Variables, operation names, aliases and fragments
  5. Root queries
  6. The Content interface and the class types
  7. The Location type
  8. Lists and pagination
  9. Filtering and sorting
  10. Search
  11. Languages and translations
  12. Images and rich text
  13. Tags, layouts, migrations and the website sidebar
  14. Mutations
  15. Uploads
  16. Drafts and preview tokens
  17. Subscriptions
  18. Persisted queries
  19. Introspection, the schema hash and code generation
  20. Errors
  21. Limits
  22. The complete core schema

End points and HTTP

End pointMethodUse
/api/graphqlPOST, GETqueries and mutations (mutations: POST only)
/api/graphql/subscribePOST, GETsubscriptions as Server-Sent Events (graphql-sse); WebSocket through Velocity
/api/graphql/playgroundGETredirects to the playground of the administration (/graphql/playground)
/graphql/queryPOSTthe 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-TypeBody
application/json (or no type and a body starting with {){"query": "...", "variables": {...}, "operationName": "...", "extensions": {...}}
application/graphqlthe query text alone
multipart/form-data with a field operationsthe GraphQL multipart request (files)
application/x-www-form-urlencodedthe 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:

HeaderMeaning
Authorization: Bearer <token>a personal API key (expk_...) or an OAuth token; none: the anonymous user. See Authentication.
X-Siteaccessthe siteaccess to answer in
Accept-Languagethe language of error messages (de-DE,de;q=0.9), never of content
If-None-Matchthe ETag of an answer you have: 304 when it is still current
X-CSRF-Tokenthe form token of a session (session end point, mutations)
Last-Event-IDthe position to resume a subscription from
Origina 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, is null (a list leaves it out).
  • errors: present when something went wrong; see Errors. data may be partial: fields without errors keep their values.
  • extensions.requestId: the id of this request (also X-Request-Id). An answer served from the response cache has no requestId in the body; the header still has one.
  • extensions.schemaHash: the hash of the schema (also X-GraphQL-Schema).

Status codes:

StatusWhen
200every answer GraphQL produced, errors included
304If-None-Match matched the current ETag
400the 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
401a credential was sent and refused ({"error":"invalid_token"}, header WWW-Authenticate); no GraphQL ran
404the API is switched off in this siteaccess (DISABLED), or subscriptions are off
429over a rate limit (RATE_LIMITED, Retry-After), a subscription limit (SUBSCRIPTION_LIMIT), or a browser check of the request shield (header Request-Shield-Challenge)
503the library webonyx/graphql-php is not installed

Answer headers:

HeaderMeaning
X-Request-Idthe request id
X-GraphQL-Schemathe schema hash
ETagthe answer's tag; weak (W/"...") for ad-hoc queries, strong for persisted queries
Cache-Controlprivate, no-store for ad-hoc queries; public, max-age=0, must-revalidate (anonymous) or private, no-cache (signed in) for persisted queries
X-GraphQL-CacheHIT, MISS (persisted queries) or BYPASS (an ad-hoc query while the cache is on)
X-Exponential-Cache-Tagsthe purge tags of what a query showed (Cache tags); never on mutations
X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Resetthe rate limit, what is left, seconds until the window ends
Retry-Afterseconds to wait, on a 429
VaryOrigin, 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

FieldArgumentsReturnsNotes
nodeexactly one of id: Int, remoteId: String, path: String, urlAlias: String; language: StringContentthe 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.
contentexactly one of id: Int, remoteId: String; version: Int (with id only); language: StringContenta 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).
previewtoken: String!Contentthe version a preview token names, until it expires; no sign-in needed
childrenparentId: Int!, classes, sortField, sortOrder, depth = 1, limit, offset, first, after, languageContentConnection!the content below a location the user may read; see Lists
searchtext, classes, subtree: [Int!], sections: [Int!], publishedAfter, publishedBefore, facets: [String!], limit, offset, first, after, languageSearchResult!see Search
currentUserUser!the user the request runs as: id, login, name, anonymous, signedInBy (anonymous, token, apikey, session, console)
siteaccessSiteAccess!name, languages (prioritized), rootNodeId, schemaHash
translations[Language!]!every content language of the installation: code, name
contentClassesidentifiers: [String!][ContentClass!]!the classes of the schema for code generators; allowed only where introspection is (INTROSPECTION_DISABLED otherwise)
tagexactly one of id, remoteId, path (keywords from the top, food/pasta); languageTageztags, while the extension is active
tagsparentId = 0, keyword, limit, offset, language[Tag!]!eztags: the tags below a tag, or every tag with a keyword
layoutexactly one of id, identifier, urlAliasLayoutExponential Layouts (explayouts): a published layout, or the layout its rules give a page
migrationStatus, migrations, migrationRuns, migrationRunsee belowthe migrations, for users with migration/read
expwtReadaction: String!, input: StringExpwtAnswer!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):

FieldTypeMeaning
idInt!the content object id
remoteIdString!the object's remote id
nameString!the name in the translation read
classIdentifierString!the class identifier (ng_article)
classNameString!the class name
published, modifiedStringISO 8601 with the server's time zone offset (2023-01-25T09:51:01-08:00)
languageString!the translation the fields are read in
languages[String!]!its translations
mainLanguageString!the language it was first written in
ownerId, ownerNameInt, Stringthe owner's object id and name
sectionIdIntits section
urlStringthe absolute address of the location it was reached by, in this siteaccess
urlAliasStringthe URL alias of that location (about/company; "" for the front page)
locationLocationthe location it was reached by (the node a query or list named, else the main one)
mainLocationLocationthe main location
locations[Location!]!every location the user may read
parentContentthe 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

FieldTypeMeaning
idInt!the node id
remoteIdStringthe location's remote id
parentIdIntthe parent's node id
depthInt!the depth in the tree (the root is 1)
pathStringString!/1/2/58/
priorityIntits priority among its siblings
hiddenBoolean!hidden itself
invisibleBoolean!hidden, or below a hidden location
urlAlias, urlStringas on Content
contentContentthe content at the location
parentContentthe content of the parent location
children(...)ContentConnection!the content below
layoutLayoutthe 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 }
  • totalCount is one count query: how many items the user may read in all.
  • nodes and edges are the same items; ask for edges only when you need the cursors.
  • Without limit or first a list returns DefaultListLimit items (25). A larger limit or first than MaxListLimit (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

ArgumentTypeMeaning
classes[String!]only content of these class identifiers; an identifier the schema does not show matches nothing
depthInt = 1how deep below the location: 1 the children, 2 children and grandchildren, a large number the whole subtree
sortFieldContentSortFieldPATH, PUBLISHED, MODIFIED, SECTION, DEPTH, CLASS_IDENTIFIER, CLASS_NAME, PRIORITY, NAME, NODE_ID
sortOrderSortOrderASC (the default) or DESC, with sortField
languageStringthe 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.

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 }
  }
}
ArgumentMeaning
textthe words, in the syntax of the installation's search engine
classesclass identifiers
subtreeonly content below these node ids
sectionsonly these section ids
publishedAfter, publishedBeforedates; ISO 8601 (2026-10-30) is the format to use. Any text PHP's strtotime() reads is accepted; another answers BAD_USER_INPUT.
facetsfacets to count (class, section, author, keywords, year ...), with an engine that has them
limit, offset, first, afteras for lists
languageonly content in this language (the engine's language filter) and read in it
  • A search needs text or at least one filter; otherwise BAD_USER_INPUT ("search needs a text or a filter ...").
  • SearchResult has totalCount (what the user may read), nodes, edges, pageInfo, engine (eZSearchEngine or eZSolr) and facets ([SearchFacet!]!: field, values { value name count }). With the kernel's own engine facets is 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; translations lists every language of the installation.
  • Without language, content is read in the first language of the siteaccess's list it has.
  • With language (on node, 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.language always says which translation you got.
  • Lists are not filtered by language (children(language: "ger-DE") still lists items that have no German translation). Filter by languages in your code, or use search(language:), which only finds content in that language.
  • url and urlAlias are 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 of image.ini; "original" is the default. An alias that does not exist answers BAD_USER_INPUT ("There is no image alias ..."). variations without aliases lists ImageAliasList[] (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.
  • RichText has html (rendered as the site renders it), text (plain), xml (stored) and excerpt(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):

RuleRefusal
mutations are on in the siteaccess (MutationsEnabled=enabled, the default)DISABLED "Mutations are switched off in this siteaccess ..."
the request is a POSTBAD_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:writeFORBIDDEN "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:

FieldMeaning
statusPUBLISHED, 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
contentIdthe object id
nodeIdthe location changed or made (the main location of new content)
versionthe version written
contentthe content now, as the user may read it (a draft: that version); null when it is gone or held by a workflow

The mutations

MutationArgumentsPolicies
createContentparentId: Int!, classIdentifier: String!, fields: [FieldInput!]!, language, remoteId, publish = truecontent/create of the class below the parent, in the language
updateContentid: Int!, fields: [FieldInput!]!, language, publish = truecontent/edit
translateContentid: Int!, language: String!, fields: [FieldInput!], publish = truecontent/edit in the new language (a role limited to languages must include it)
publishDraftid: Int!, version: Int!the user's own draft, or one the user may read and edit
deleteContentexactly one of id: Int (every location) and nodeId: Int (one); trash = truecontent/remove
moveContentnodeId: Int!, newParentId: Int!content/edit and content/remove here, content/create there
hideContent / revealContentnodeId: Int!content/hide
addLocationid: Int!, parentId: Int!content/edit of the object, content/create below the new parent
assignSectionnodeId: 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
setObjectStatesid: 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
restoreContentid: Int!, parentId: Intcontent/restore and content/create below the parent (the original one by default)
uploadImagefile: Upload!, parentId: Int!, name, alt, classIdentifier = "image", fieldIdentifier = "image", nameIdentifier = "name", language, publish = trueas createContent
uploadFromUrlurl: String! and the arguments of uploadImage without fileas createContent; only hosts of UploadFromUrlHostList[]
createPreviewTokenid: Int!, version, language, ttlreading 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 MaxUploadSize bytes (32 MB by default; PHP's upload_max_filesize and post_max_size apply first).
  • Every file passes the checks of UploadCheckList[] (classes implementing expGraphQLUploadCheck: a virus scanner, a type filter); the first that gives a reason refuses it.
  • uploadFromUrl(url:) fetches an https address of a host in UploadFromUrlHostList[] (no redirects, at most MaxUploadSize); 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:

  1. 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 version the token names the user's newest draft, else the published version. ttl defaults to PreviewTokenTtl (3600 s) and is capped at MaxPreviewTokenTtl (86400 s).

  2. 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 --apply

Each 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 BYPASS

By 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.

SettingValuesEffect
PersistedQueriesenabled (default), disabledoff: an id or hash answers PERSISTED_QUERY_NOT_SUPPORTED
AutomaticPersistedQueriessigned-in (default), enabled, disabledwho may store by sending text and hash
PersistedQueriesOnlydisabled (default), anonymous, enabledonly 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 by Introspection: signed-in (the default: a key, a token, a session), enabled (everybody) or disabled (only the console). Refused: INTROSPECTION_DISABLED.
  • contentClasses(identifiers:) lists the classes of the schema with each field's identifier, fieldName, datatype, graphqlType, mapped (the datatype has a mapping of its own), required, translatable, searchable and options (selection options): what @exponentialcms/codegen reads. 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-Schema in your build.
  • The console prints the schema without the API being on: ./console exp:graphql:schema --siteaccess=site (--format=sdl default, json the introspection result, summary the classes and the datatypes that fall back to String), --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.codeHTTPMeaningWhat to do
PARSE200not valid GraphQL syntaxfix the query (the message names line and column)
VALIDATION200does not fit the schema: an unknown field, a wrong argument type, a missing fragmentcheck the schema; the class or attribute may be hidden, or the naming style differs
BAD_USER_INPUT200 (400 for an unreadable request)an argument is wrong, or the request cannot be readread the message; it names the argument
DEPTH_LIMIT200deeper than MaxDepthflatten the query
COMPLEXITY_LIMIT200more complex than MaxComplexitylower limit/first, split nested lists
INTROSPECTION_DISABLED200this request may not read the schemasign in, or use the console
DISABLED404 (200 for mutations)the API is off in this siteaccess, mutations or subscriptions are offswitch it on, or use the right siteaccess
FORBIDDEN200 (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-insign in, give the key graphql:write, give the role the policy
NOT_FOUND200a mutation on content that is not there or not readable (a query answers null instead)check the id and the user's read rights
INTERNAL200 (503 without the library)an error in the codequote the request id; the server log has the details
PERSISTED_QUERY_NOT_FOUND200no persisted query has this id or hashstore it, or send the text
PERSISTED_QUERY_NOT_SUPPORTED200persisted queries are offsend the text
PERSISTED_QUERY_REQUIRED200an ad-hoc query where only persisted queries are acceptedpersist the query and send its id
RATE_LIMITED429over the rate limitwait Retry-After seconds
SUBSCRIPTION_LIMIT429too many open subscriptionsclose one; try later

Messages you will meet, with their code:

MessageCode
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 errorINTERNAL

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

SettingDefaultError
MaxQueryLength100000 bytesBAD_USER_INPUT
MaxDepth12DEPTH_LIMIT
MaxComplexity1000COMPLEXITY_LIMIT
MaxListLimit100(lowered silently)
DefaultListLimit25
RateLimit / RateLimitAnonymous / RateLimitPublicKey per RateLimitWindow600 / 120 / 3000 per 60 sRATE_LIMITED
MaxUploadSize32MBAD_USER_INPUT
MaxPersistedQueries1000(not stored; runs ad hoc)
MaxSubscriptions, MaxSubscriptionsPerUser, MaxSubscriptionsPerAddress200, 5, 10SUBSCRIPTION_LIMIT
Purge tags per answer500 (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.

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x