GraphQL

/graphql/v1 with the schema conventions of Supabase’s GraphQL: collections, filters, ordering, relationships and mutations, under row-level security.

/graphql/v1 serves the same tables, views and functions as /rest/v1 as a GraphQL API, with the schema conventions of Supabase's GraphQL (pg_graphql): <type>Collection connections, node(nodeId:), filters and orderings per column, insertInto/update/deleteFrom<type>Collection mutations, and relationships from foreign keys. Apollo, urql, graphql-request, GraphiQL and GraphQL codegen work against it as they do against Supabase.

Every request runs as the caller, exactly like REST: the anon key alone runs as anon, a signed-in person's access token as authenticated (with their claims, so auth.uid() works in policies), the service key as service_role. Grants and row-level security decide what each sees and changes; nothing else does.

TypeScript
const res = await fetch(`${FORKBASE_URL}/graphql/v1`, {
  method: "POST",
  headers: { apikey: ANON_KEY, Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
  body: JSON.stringify({ query: "{ todosCollection(first: 10) { edges { node { id title } } } }" }),
});
const { data, errors } = await res.json();

Requests

  • POST /graphql/v1 with {"query": "...", "variables": {...}, "operationName": "..."} (variables and operation name optional), or the document itself with Content-Type: application/graphql.
  • GET /graphql/v1?query=...&variables=<JSON>&operationName=...: queries only; a mutation is sent with POST.
  • The apikey header (and Authorization: Bearer <access token> for a signed-in person), as for REST.

The answer is {"data": {...}} with status 200. Anything that fails gives {"data": null, "errors": [{"message", "locations"?}]}, still status 200: a syntax error, a field or argument the schema lacks, a wrong variable, a refusal by the database (its own message: a policy, a constraint). A missing or invalid key is status 401. Subscriptions are not served: listen to changes over realtime.

Documents may use variables (with defaults), fragments, inline fragments, aliases, several operations picked by operationName, @skip and @include, and __typename anywhere.

The schema

It is made from the served schemas (rest.schemas) and made again whenever REST reads them again: every 30 seconds, and at once when a request names a root field the schema lacks, so a table made a moment ago is found.

Per role. Each role sees only what it was granted, as with pg_graphql: a table appears if the role may select, insert, update or delete it; its collection only with select, and each mutation only with that privilege; a function only if the role may execute it. So introspect with the key you will use. A table is closed to anon and authenticated until you grant it to them.

Names. By default names are the database's own (blog_post, blog_postCollection, created_at). To get camelCase, as most GraphQL clients expect, inflect the schema's names, as with pg_graphql:

SQL
comment on schema public is e'@graphql({"inflect_names": true})';

Then blog_post is the type BlogPost, its collection blogPostCollection, its column created_at the field createdAt. A comment can rename one thing, and the rest of the comment becomes its description:

SQL
comment on table public.blog_post is e'Posts. @graphql({"name": "Post"})';
comment on column public.blog_post.body is e'@graphql({"name": "text"})';
comment on function public.search_posts is e'@graphql({"name": "search"})';
comment on view public.recent is e'@graphql({"primary_key_columns": ["id"]})';
comment on schema public is e'@graphql({"inflect_names": true, "max_rows": 50})';

A name that isn't a valid GraphQL name (spaces, dashes) is left out. Two served schemas with a table of the same name: the second's type is prefixed with its schema.

Scalars. As pg_graphql maps them:

PostgresGraphQL
smallint, integerInt
bigintBigInt (a string, so no digits are lost)
real, double precisionFloat
numericBigFloat (a string)
text, varchar, charString
booleanBoolean
uuidUUID
dateDate
timestamp, timestamptzDatetime
timeTime
json, jsonbJSON (the JSON's text, as a string, both ways)
an enuman enum of the same name, its labels as values
an arraya list of the element's scalar
anything elseOpaque (the value as JSON)

Reading

For every table and view the role may select, Query has a collection, a Relay connection:

graphql
{
  blogPostCollection(
    first: 10                          # or last: 10
    after: "WyIyIl0="                  # or before: a cursor
    offset: 0
    filter: { title: { ilike: "%news%" }, or: [{ id: { lt: 5 } }, { published: { eq: true } }] }
    orderBy: [{ createdAt: DescNullsLast }, { id: AscNullsFirst }]
  ) {
    totalCount
    pageInfo { hasNextPage hasPreviousPage startCursor endCursor }
    edges {
      cursor
      node {
        nodeId
        id
        title
        blog { name }                                   # to-one: this row's foreign key
        commentCollection(first: 5) { edges { node { body } } }   # to-many: rows whose key points here
      }
    }
  }
}
  • Paging. first or last (not both) rows, after or before a cursor, after offset rows. Without first or last a page is 30 rows (the schema's max_rows directive changes it); no page is longer than that or rest.max_rows. Cursors are keyset positions in the page's order (its orderBy, then the primary key), so a page stays right when rows are added before it; a cursor made for one order is refused for another. A table or view without a primary key has no nodeId and pages forward only (first, after, offset; its cursors are positions).
  • Filters. Per column, by type: eq, neq, gt, gte, lt, lte, in, is: NULL | NOT_NULL; text also like, ilike, startsWith, regex, iregex; lists contains, containedBy, overlaps, eq, is. Several in one object must all hold; and: [...], or: [...] and not: {...} combine them; nodeId: {eq: ...} picks a row. JSON columns have no filter.
  • Order. orderBy is a list, one column per item, with AscNullsFirst, AscNullsLast, DescNullsFirst or DescNullsLast. The primary key is always last, so the order is total.
  • Relationships follow single-column foreign keys between tables the role may select. The referencing side gets the row it points to, named after the column without _id (blog_id gives blog), else after the table it points to. The other side gets a collection of the rows pointing to it (<type>Collection, paged and filtered like any), or one row when the key column is that table's whole primary key.
  • node(nodeId: ID!) reads any row back by its nodeId (its schema, table and primary key, base64-encoded JSON, as pg_graphql makes them). Use fragments for its fields: node(nodeId: $id) { ... on BlogPost { title } }.
  • totalCount counts the rows the filter matches, all pages together. It is computed only when asked for.

A query is one SQL statement, however many collections and relationships it nests: each is a correlated subquery building JSON, never a query per row. Tables nest at most 16 deep.

Writing

For every table the role may insert into, update or delete from, Mutation has:

graphql
mutation {
  insertIntoBlogPostCollection(objects: [{ title: "Hello", blogId: "1" }, { title: "Again", blogId: "1" }]) {
    affectedCount
    records { id title }
  }
  updateBlogPostCollection(set: { title: "Edited" }, filter: { id: { eq: 1 } }, atMost: 1) {
    affectedCount
    records { nodeId title }
  }
  deleteFromBlogPostCollection(filter: { title: { like: "draft%" } }, atMost: 5) {
    affectedCount
  }
}
  • An insert's rows may name different columns; a column a row leaves out takes its default.
  • atMost (default 1) guards updates and deletes: if more rows than that would change, nothing changes and the request fails. Without a filter every row the caller's policies let them change is matched, so atMost is what stops an accidental change of everything.
  • records returns the changed rows, read as the caller (their select policies apply to them too).
  • Root fields run in order, in one transaction: if any fails, none of them is kept.

Functions

Functions of the served schemas become fields, as with pg_graphql: stable and immutable ones on Query, volatile ones on Mutation, named after the function (inflected like the rest), with their arguments by name. An argument without a default is required.

  • One value: a scalar field (addOne(n: 41)); setof values: a list.
  • One row of a served table (returns blog_post): that type.
  • Rows of a served table (returns setof blog_post): a collection, with first, last, after, before, offset, filter and orderBy (a mutation function's rows are computed once).
  • returns void: Opaque, always null.

Overloaded functions, functions with an unnamed argument, and functions returning table(...) or record are left out (call them over /rest/v1/rpc).

Introspection

__schema and __type(name:) are answered from the schema without touching the database, so GraphiQL, Apollo codegen, graphql-codegen and IDE plugins can load it. Introspect with the key your app uses: the schema is that role's.

In the dashboard

API docs > GraphQL (/dashboard/api/graphql/) is a GraphiQL-style page: a query editor with variables, the answer, and a schema explorer to browse types, fields and arguments. It runs with the anon key or, for admins, the service key.

Compared with Supabase

The paths, names, arguments and answers follow pg_graphql. Beyond it: totalCount is always offered (pg_graphql needs a directive), tables without a primary key are served (forward paging only), and GET works for queries. Not served: subscriptions, computed fields from functions taking a row, @graphql directives on foreign keys and enum values, and aggregates.

Something wrong or missing? Edit this page on GitHub or open an issue.

GraphQL · Forkbase