GraphQL API Technical Reference

Prismic’s GraphQL API is a read-only endpoint that allows you to perform deep fetching and selective fetching for documents from your Prismic repository.

Copy
https://your-repo-name.cdn.prismic.io/graphql

Every Prismic repository includes a GraphQL API explorer that will help you discover your API and test your queries:

Copy
https://your-repo-name.prismic.io/graphql

The GraphQL Explorer is divided into two parts: the left part lets you build a query, and the right part shows the query results. It offers an autocompletion feature that helps you to build your query. By hitting ctrl + space, you will be able to see all the options.

GraphQL clients such as Apollo Client or graphql-request can be used to query Prismic. The following code snippets show how to set up your GraphQL client with Prismic.

  • Apollo Client
  • GraphQL Client
Apollo Client
prismicio.js
Copy
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'
import * as prismic from '@prismicio/client'

// Fill in your repository name
export const repositoryName = 'your-repo-name'

const prismicClient = prismic.createClient(repositoryName, {
  // If your repository is private, add an access token
  accessToken: '',

  // This defines how you will structure URL paths in your project.
  // Update the types to match the custom types in your project, and edit
  // the paths to match the routing in your project.
  //
  // If you are not using a router in your project, you can change this
  // to an empty array or remove the option entirely.
  routes: [
    {
      type: 'page',
      path: '/:uid',
    },
  ],
})

export const client = new ApolloClient({
  link: new HttpLink({
    uri: prismic.getGraphQLEndpoint(repositoryName),
    fetch: prismicClient.graphQLFetch,
    useGETForQueries: true,
  }),
  cache: new InMemoryCache(),
})
GraphQL Client
prismicio.js
Copy
// GraphQL Client - prismicio.js

import { GraphQLClient } from 'graphql-request'

// The rest of the file...

export const client = new GraphQLClient(
  prismic.getGraphQLEndpoint(repositoryName),
  {
    fetch: prismicClient.graphqlFetch,
    method: 'get',
  }
)

Every GraphQL query has a query name, a root field, and content fields. The query name consists of the word query followed by a unique name that should be descriptive of your query. Query names are usually PascalCased.

Inside queries that return multiple results are edges and nodes. Edges and nodes are how GraphQL structures data. Edges connect related nodes together. Nodes contain data retrieved by GraphQL.

Copy
query ExampleAllDocsQuery {
  _allDocuments {               # root field
    edges {                     # the array of results
      node {                    # an individual result
        example_title           # a content field
        example_group {         # a repeatable group field
          example_number        # a content field inside a group field
        }
        _meta {                 # result metadata
          id                    # result id
        }
      }
    }
    pageInfo {                  # pagination information
      hasNextPage               # whether there is another page
    }
  }
}

query ExampleSingleQuery {                                 # query definition
  example_singleton_type(uid: "example", lang: "en-US") {  # root field with arguments
    example_title
  }
}

Root fields

The root field defines the entry point of your query.

  • To write a get-all query, set the root field to _allDocuments.
  • To write a get-all-by-type query, set the root field to all{Type_id}s where Type_id is the snake_cased API ID for the type with the first letter capitalized (e.g. allBlog_posts). The Type_id must be appended by an s.
  • To write a get-single query, set the root field to {type_ID} where Type ID is the API ID of your type. Then, use the variables uid and lang to query the document with a specific UID and language (e.g. blog_post(uid:"hello-world", lang:"en-US"))

For a get-single query, the root field will contain the content and metadata fields for the document returned.

Copy
query GetSingle($uid: String, $lang: String) {
  example_custom_type(uid: $uid, lang: $lang) {
    example_rich_text
  }
}

For get-all and get-all-by-type queries, the root field will contain pagination info and an edge, which will contain the results as nodes. Each node will contain content fields and metadata fields.

Copy
query GetAllByType {
  allExample_custom_types {
    edges {
      node {
        example_rich_text
      }
    }
  }
}

Pagination fields

Pagination fields are the six pagination fields used to build cursor-based pagination:

pageInfo {
  hasPreviousPage
}

boolean

Specifies if there is a page of results before the current page

pageInfo {
  hasNextPage
}

boolean

Specifies if there is a page of results after the current page

pageInfo { 
  startCursor 
}

string

The cursor of the item that starts the current list

pageInfo { 
  endCursor 
}

string

The cursor of the item that ends the current list

edges { 
  cursor 
}

string

An ID to query the documents that come before or after.

totalCount

number

The total number of items across all the pages of the query

There are four arguments with cursors to retrieve paginated results from your GraphQL API: after, before, first, and last.

Once you have a given cursor, you can use the after argument to retrieve the documents that come after it. This works with the first argument to specify how many items to retrieve (up to 100).

Copy
query PaginatedPosts {
  allBlog_posts(after: "YXJyYXljb25uZW", first: 99) {
    edges {
      node {
        example_rich_text
      }
    }
  }
}

Content fields

Content fields determine the data returned from your query. Most fields can be selected with just their API ID. A repeatable group field will also contain nested fields. Links and relationships must be selected with a union.

Timestamp, Date, Color, Number, Key Text, Select, Title, Rich Text, Image, Embed, Geopoint, and Boolean

Select these fields directly by their API ID (e.g. example_color_field)

Repeatable group

Select a repeatable group field by its API ID and then the IDs of fields contained within (e.g. example_group_field { example_color_field })

Link, Link to Media, and Content Relationship

Use unions. (See the Unions section.)

Metadata fields

Metadata fields are the eight document metadata fields that are returned from the _meta object:

  • id
  • uid
  • type
  • tags
  • lang
  • firstPublicationDate
  • lastPublicationDate
  • alternateLanguages

Arguments

Arguments are parameters that you can add to filter the GraphQL response. They can be either static or dynamic. If they're dynamic, you can pass your values in the form of variables.

For example, you can use the fulltext argument to search for documents that contain a given term (or terms). It performs a case-insensitive search for the term(s) in any rich text, title, key text, uid, or select fields in a document.

Copy
query FullTextArgument {
  allPages(fulltext: "Art") {
    edges {
      node {
        example_rich_text
      }
    }
  }
}

You can filter the response using with the following arguments:

fulltext

string

fulltext: "dog"

uid

string

uid: "art"

uid_in

array of strings

uid_in: ["music", "games", "paintings"]

id

string

id: "WiU34h0AAI90y1m2"

id_in

array of strings

id_in: ["EsdGHJt5df7", "WiU34h0AAI90y1m2"]

lang

string

lang: "en-us"

tags

string

tags: "article"

tags_in

array of strings

tags_in: ["article", "guide", "news"]

firstPublicationDate_after

date

firstPublicationDate_after:"2022-05-12T15:47:11+0000"

firstPublicationDate_before

date

firstPublicationDate_before:"2022-05-12T15:47:11+0000"

lastPublicationDate_after

date

lastPublicationDate_after:"2022-05-12T15:47:11+0000"

lastPublication_before

date

lastPublicationDate_before:"2022-05-12T15:47:11+0000"

Use the where argument with content fields at the top level of your documents to filter out the response. Only fields at the top level of your document are available for filtering. Fields inside slices aren't available.

The where field accepts a single key-value pair, specifying a field and a value to compare against. The type of comparison can be specified with a suffix, such as _lt (less than) or _gt (greater than).

With no suffix, the API will search for a direct match.

Number greater than

float

Filter for a number field greater than a given number.

where: {example_number_field_gt: 97}

Number less than

float

Filter for a number field less than a given number.

where: {example_number_field_lt: 98}

Before date

string

Filter for a date field before a given date.

where: {example_date_field_before: "2022-01-22"}

After date

string

Filter for a date field after a given date.

where: {example_date_field_after: "2022-01-22"}

Number in range

array of integers

Filter for a number field that is within a given range.

where: {example_number_field_range:[1,3]}

Geopoint near

object

Filter for a geopoint field that is within a given distance of a given location

where: {example_geopoint_field_near: {lat: 20.6, lng: 0.02, dist: 10 }}

Use the similar argument with an object containing the ID of a document. The max value you need to provide above will determine how sensitive the filter is. It represents the maximum number of documents that a term may appear in to remain relevant.

This means that the higher the value, the more documents will be returned. A lower maximum value will return fewer documents.

The sortBy argument orders the results by a specific field prepended with either an _ASC (ascending order) or _DESC (descending order) option.

These fields can be a metadata publication date or a top-level content fields (fields inside slices or repeatable groups are unavailable).

  • meta_lastPublicationDate ascending or descending
  • meta_firstPublicationDate ascending or descending
  • Rich text field
  • Title field
  • Key text field
  • Select field
  • Date field
  • Timestamp field
  • Number field

Unions

Unions are used to query nested content such as slices and content relationship. The union is used inside queries to specify the data needed from a parent field using spread syntax.

Slices

To query data in a slice, add a union inside the body field. The syntax for a slice union is …on, followed by the type API ID, Body, and the slice API ID. For example, ...on ExampleCustomTypeBodySlice. Inside the union, there are four properties:

  • label is the name of the slice.
  • type is the type associated with the slice.
  • primary contains the fields in the static zone.
  • fields contains the fields in the repeatable zone (deprecated).

To query a field in a slice, add the field’s API ID inside primary if it’s in the static zone or fields if it’s in repeatable zone (deprecated).

Copy
query GetSliceFields {
  page(uid: "jazz", lang: "en-us") {
    body {
      ...on PageBodyPlaylist {
        label
        type
        primary {
          playlist_name
        }
        fields {
          song
          author
        }
      }
    }
  }
}

Content relationships

To query data in a content relationship, add a union inside the field API ID content field. The syntax for a content relationship union is ..._Document. Inside the union, there is the _typename property.

Inside _typename, add the query for the data you wish to retrieve from the linked document.

Copy
query GetContentRelationshipFields {
  allPages {
    edges {
      node {
        example_content_relationship {
          ...on _Document {
            __typename
            _meta {
              id
              uid
              lang
            }
          }
        }
      }
    }
  }

Links

To query data in a link or link to media field, add a union inside the field API ID content field. The syntax for a link field union is …on _ExternalLink and for a link to media field union is …on _ImageLink.

Inside the union, add the property you wish to retrieve. For more information on link or link to media field properties, see the Field article.


Can't find what you're looking for?

Need technical Support? Spot an error in the documentation? Get in touch with us on our Community Forum.