Fetch Data

Prismic offers different methods to query content into your project via the Rest API.


Before reading

This article assumes that you have already set up an Express project with Prismic and run it with nodemon. If you haven't, see Install Prismic.

Perform a query

In Express, you can define your routes and query in the main file (in the setup step, we used index.js).

Here's an example of a typical query for a homepage route. It will query a singleton document from your repo of the type "homepage" and render an EJS page with the fetched data.

Copy
app.get('/', async (req, res) => {
  const document = await client.getSingle('homepage')
  res.render('page', { document })
})

List of query helpers

Here are the most commonly-used helpers:

getSingle()

Copy
getSingle(type)
getSingle(type, params)

Queries a singleton document from the Prismic repository for a specific Custom Type Here type refers to the API ID of the Custom Type.

For example, here we are querying for the single instance of the Custom Type "Homepage".

Copy
const document = await client.getSingle('homepage')

getByUID()

Copy
getByUID(type, uid)
getByUID(type, uid, params)

Queries the document from the Prismic repository with a given UID and Custom Type. Here type refers to the API ID of the Custom Type, and uid refers to the document's UID.

Copy
const document = await client.getByUID('post', 'my-first-post')

getByID()

Copy
getByID(id)
getByID(id, params)

Queries a document from the Prismic repository with a specific ID.

Copy
const document = await client.getByID('X9C6UxEAAJFIAuBg')

getAllByType()

Copy
getAllByType(type)
getAllByType(type, params)

Queries all documents from the Prismic repository for a specific Custom Type. Here, type refers to the API ID of the Custom Type. This method may perform multiple network requests. It returns an array containing all matching documents from the repository.

Copy
const documents = await client.getAllByType('article')

getAllByIDs()

Copy
getByIDs(arrayOfIDs)
getByIDs(arrayOfIDs, params)

Queries all documents from the Prismic repository with given IDs and returns them in the order provided.

Copy
const documents = await client.getAllByIDs([
  "WW4bKScAAMAqmluX", "U1kTRgEAAC8A5ldS",
])

Query parameters

All query methods can accept a params object, specifying API options. Some useful options are:

  • predicates
  • lang
  • ordering
  • fetchLinks and graphQuery

A query with params looks like this:

Copy
const documents = await client.getAllByType('article', {
  lang: 'fr-fr',
  fetchLinks: 'author.name'
})

Below, we'll explain some useful query options. For more in-depth information on API options, see the Rest API reference.

predicates

predicates are search filters, and Prismic has dozens of them. Most (but not all) predicates take the format of:

Copy
predicate( path, value )

The predicate would be the name of the specific predicate method. The path defines the field to examine on each document. The value is the value to compare against.

To use the predicate methods, you must first import @prismicio/client:

Copy
import * as prismic from '@prismicio/client'

A predicate looks like this:

Copy
prismic.predicate.at('my.author.birthday', '2020-06-20')

Here are some examples of paths that predicates can accept. (Note: not all predicates can accept all paths. See the predicate reference for more details.)

  • my.[custom-type].[uid-field]
  • my.[custom-type].[key-text-field]
  • my.[custom-type].[select-field]
  • my.[custom-type].[number-field]
  • my.[custom-type].[date-field]

Three commonly-used predicates are at()not(), and any().

The at() predicate will search for an exact match. The following query will search for all documents where the type is a product with a price of 20.

Copy
{
  predicates: prismic.predicate.at('my.product.price', 20)
}

The not() predicate will filter for documents that do not match the given value. The following query will search for all documents where the type does not match homepage.

Copy
{
  predicates: prismic.predicate.not('document.type', 'homepage')
}

The any() predicate will check for a field that matches any value in an array. The following query will search for all product documents where a Select field called climate matches desert, beach, or rainforest.

Copy
{
  predicates: prismic.predicate.any('my.product.climate', ['desert', 'beach', 'rainforest'])
}

lang

The lang param specifies what locale to query from. If you don't specify a lang, the system will query the documents in the master locale by default. The following query will search for all documents of the type blog-post in the locale fr-fr.

Copy
const documents = await client.getAllByType('blog_post', {
  lang: 'fr-fr',
})

orderings

The orderings parameter tells the API to order your results by a specific field. It accepts an orderings object or an array of orderings objects.

The ordering object has a field(which accepts a path) and an optional direction property (which can be either "desc" or "asc" and defaults to "asc").

In the following example, the orderings param sorts the documents by price from highest to lowest.

Copy
{
  orderings: {
    field: 'my.post.price',
    direction: 'desc'
  }
}

fetchLinks and graphQuery

As described in the section on templating links, you can use API options to pull in data from a linked document. There are two ways to do this.

The first option is fetchLinks, which is a concise way to pull in a property (or array of properties) from a linked document. For more information, see the fetchLinks documentation.

The second option is GraphQuery. GraphQuery uses a syntax similar to GraphQL. It's a little more complex than fetchLinks, but allows you to fetch content multiple levels deep (from a linked document on a linked document, for example), and fetch content selectively. For more information, see the GraphQuery documentation.

Use cases

Here are a few common use cases.

Query a nav menu or config document

In Prismic, you can create a singleton Custom Type to store site components, such as a header, footer, menu, or config file.

To query a singleton, use the getSingle() method.

Copy
// Fetch menu content from Prismic
app.get('*', async (req, res, next) => {
  const menuContent = await client.getSingle('menu')
  // Add the menu to local variables
  res.locals.menuContent = menuContent
  next()
})

Query one instance of a repeatable document

We recommend including a UID field — a unique identifier — on repeatable documents. Prismic makes UIDs URL-friendly and unique to each Custom Type.

To query a specific document of a given Custom Type, like a blog post, you can use the getByUID() method.

To use getByUID(), pass the UID and the API ID of the Custom Type.

Copy
// Page route
app.get('/:uid', async (req, res) => {
  const uid = req.params.uid
  const document = await client.getByUID('page', uid)
  res.render('page', { document })
})

Query all documents

There are three ways to get all documents.

  • You can query all documents of a particular type with getAllByType() (recommended).
  • You can query a paginated list of all documents from your repository, regardless of type, using get(). This will return a paginated response, including the first 100 documents.
  • To query an unpaginated list of all documents regardless of type, use dangerouslyGetAll(). Since the payload can be large, this method can cause performance issues, and it is not recommended.
Copy
// Homepage route
app.get('/', async (req, res) => {
  const response = await client.getAllByType('page')
  res.render('page', { response })
})

Query by language

Prismic allows you to publish your content in different languages. If left unspecified, the API returns content in the master locale. To get content in a different locale, add an options object with the lang option and a locale code. Here's an example of how to query a 'homepage' document in French ('fr-fr').

Copy
// Homepage route with language option
app.get('/', async (req, res) => {
  const document = await client.getSingle('homepage', { lang: 'fr-fr' })
  res.render('page', { document })
})

Query by date

To query content based on a specific date, use the at() predicate with a Date field:

Copy
const response = await client.get({
  predicates: prismic.predicates.at('my.author.birthday', '2020-06-20'),
})

Query by a Content Relationship

The Content Relationship field can be used to create content taxonomies. To query by Content Relationship, use the at() predicate with the path my.[custom-type].[content-relationship-field] and the ID of the linked document:

Copy
const response = await client.get({
  predicates: prismic.predicates.at(
    'my.blog_post.category_link',
    'WNje3SUAAEGBu8bc'
  ),
})

Note: To query by Content Relationship, you must use the linked document's ID. The ID is a randomly-generated string that looks like this: WNje3SUAAEGBu8bc. You can find it in the metadata of the document's API result.

Query by a Content Relationship field in a Group

If your Content Relationship field is inside a group, use the at predicate with the path my.[custom-type].[group-field].[content-relationship-field] and the ID of the linked document.

Copy
const response = await client.get({
  predicates: prismic.predicates.at(
    'my.blog_post.category_link',
    'WNje3SUAAEGBu8bc'
  ),
})


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Get in touch with us on our Community Forum.