Fetch Data

This technology has no Slice Machine integration

This framework has no integration with Prismic's developer tool, Slice Machine. You can still build a Prismic website with this technology by using Prismic's Legacy Builder. However, if you're starting a new project with Prismic, we strongly recommend using a technology that integrates with Slice Machine: Next.js or Nuxt.

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:

  • filters
  • 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.

filters

filters are a way to refine your query, and Prismic has dozens of them. Most (but not all) filters take the format of:

Copy
filter( path, value )

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

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

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

A filter looks like this:

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

Here are some examples of paths that filters can accept. (Note: not all filters can accept all paths. See the filter 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 filters are at()not(), and any().

The at() filter 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
{
  filters: prismic.filter.at('my.product.price', 20)
}

The not() filter 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
{
  filters: prismic.filter.not('document.type', 'homepage')
}

The any() filter 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
{
  filters: prismic.filter.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() filter with a date field:

Copy
const response = await client.get({
  filters: prismic.filter.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() filter with the path my.[custom-type].[content-relationship-field] and the ID of the linked document:

Copy
const response = await client.get({
  filters: prismic.filter.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 filter with the path my.[custom-type].[group-field].[content-relationship-field] and the ID of the linked document.

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


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.