Fetch Data

This section will teach you how to connect to the API of your Prismic repository and how to create queries to retrieve documents.

Before your proceed

We strongly recommend building your app with a JavaScript framework, like Express, React, or Vue. If you choose to use vanilla JavaScript, you'll first need a project configured with Prismic. If you don't have one yet, start with the Setup step.

Define client options

The client object has methods for querying the Prismic API. If you haven't already, create a Prismic API client using the @prismicio/client package. The getEndpoint() method formats your repo name as an API endpoint URL. createClient() creates a client object with the endpoint.

createclient() accepts an optional access token (if your repository is private), a routes object to define the URL structure for each document's url property, and other options. See all available options in the @prismicio/client Technical Reference.

  • Node.js
  • Browser
Copy
import * as prismic from '@prismicio/client'
import * as prismicH from '@prismicio/helpers'

const endpoint = prismic.getEndpoint('your-repo-name')
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(endpoint, { routes, accessToken })
Copy
import * as prismic from 'https://cdn.skypack.dev/@prismicio/client'
import * as prismicH from 'https://cdn.skypack.dev/@prismicio/helpers'

const endpoint = prismic.getEndpoint('your-repo-name')
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(endpoint, { routes, accessToken })

Update routes

You must update the routes array to match the Custom Types in your repository. If you name a Custom Type that does not exist in your repository, the API query will error.

From here you can start using client to create queries like the following one that retrieves a document of the singleton type "home":

Copy
const init = async () => {
  client.getSingle('home')
}

init()

Putting it all together, all queries will happen inside the init function:

  • Node.js
  • Browser
Copy
import * as prismic from '@prismicio/client'
import * as prismicH from '@prismicio/helpers'

const endpoint = prismic.getEndpoint('your-repo-name')
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(endpoint, { routes, accessToken })

const init = async () => {
  /*
  All operations happen here
  */
}

init()
Copy
import * as prismic from 'https://cdn.skypack.dev/@prismicio/client'
import * as prismicH from 'https://cdn.skypack.dev/@prismicio/helpers'

const endpoint = prismic.getEndpoint('your-repo-name')
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(endpoint, { routes, accessToken })

const init = async () => {
  /*
  All operations happen here
  */
}

init()

The @prismicio/client kit offers query helper options to search for your documents.

Query methods

The query methods help you filter your documents. They are divided into three main categories:

  • paginated get methods
  • get-all methods
  • get-single methods

Further Learning

There are many more methods for querying the API. All of these queries can accept options to filter, sort, paginate, and translate your query response. See them all in the @prismicio/client Technical Reference.

Here are the most commonly-used query methods:

getByUID()

Accepts the UID of a document and an optional params object. Returns the document that matches the given Custom Type and UID.

Copy
client.getByUID(customType)
client.getByUID(customType, params)

For example, here we are querying for a page document with a UID of february-news.

Copy
const prismicDoc = await client.getByUID('page', 'february-news')

getSingle()

This method accepts a Single Custom Type API ID and an optional parameters object. It returns the document associated with the given Single type.

Copy
client.getSingle(customType)
client.getSingle(customType, params)

For example, here we are querying for the only document of the Custom Type home.

Copy
const prismicDoc = await client.getSingle('Home')

getFirst()

This method accepts an optional params object. It returns the first document that matches the search.

Copy
client.getFirst()
client.getFirst(params)

This example will return the most recent document from the repository:

Copy
const prismicDoc = await client.getFirst()

getAllByType()

This method accepts the API ID of a Custom Type, and an optional params object. It returns all the documents that match the Custom Type.

Copy
client.getAllByType(customType)
client.getAllByType(customType, params)

For example, here we are querying for all documents of the Custom Type blog_post.

Copy
const results = await client.getAllByType('blog_post')

getAllByIDs()

This method accepts an array of document ID strings and an optional params object. It returns all the documents that match the given IDs.

Copy
client.getAllByIDs(arrayOfIDs)
client.getAllByIDs(arrayOfIDs, params)

In the following example returns the documents that match the given IDs.

Copy
const results = await client.getAllByIDs(['WAjgAygAAN3B0a-a', 'WC7GECUAAHBHQd-Y'])

Params object

All of the query helper methods accept a params object. See the following usage examples.

accessToken

Accepts the access token for your repository, as a string. Is required if your repository is private.

Copy
{ accessToken: 'MC5ZVnRWUnhBQUFDWUE3N2tN.77...' }

fetchLinks

Retrieves content from a linked document. Formatted as '[custom-type].[field]'.

Copy
{ fetchLinks : 'author.first_name' }

lang

Accepts a locale code as a string or '*' to return all languages. Specifies what language to return. By default, the API will return content from the master locale.

Copy
{ lang: 'fr-fr' }

Learn more about the parameters object in the @prismicio/client Technical Reference.

predicates

Predicates are query filters. There are dozens of predicates available with @prismicio/client.

Most predicates follow the following pattern: [q] is a query predicate, the path is a string that specifies the field being examined, and value specifies the value to evaluate against.

Copy
{
  predicates: [prismic.predicate.[q](path, value)]
}

Here are some examples of the most commonly-used predicates.

at() filters for documents where the path matches a given value:

Copy
prismic.predicate.at('my.product.category', 'shoes')

not() filters for documents where the path does not match a given value:

Copy
prismic.predicate.not('my.product.category', 'shoes')

any() filters for documents where the path matches any value from an array:

Copy
prismic.predicate.any('my.product.category', ['shoes', 'jackets', 'blouses'])

Read the complete predicates documentation in the Rest API Technical Reference.

Usage examples

Here you'll find a list of common use cases that showcase how you can mix and match query methods, query options, and predicates to make your queries as specific as you need.

Filter by a field

The my.[custom-type].[field] path allows you to query documents by specific fields: Boolean, Number, Key Text, Select, Group, and Content Relationship fields. You can use one or more predicates in a single query.

Here is a basic filter by field:

Copy
client.getAllByType('product', {
  prismic.predicate.at('my.product.category', 'shoes')
})

Prismic also includes predicates to filter by numbers and dates. This example will return all movies released in June 2022:

Copy
client.getAllByType('movie', {
  predicates: [
    prismic.predicate.month('my.movie.release-date', 'June'),
    prismic.predicate.year('my.movie.release-date', 2022),
  ],
})

Filter by a Content Relationship

To query by a Content Relationship, use the ID of the linked document.

Copy
client.getAllByType('blog_post', {
  predicates: [
    prismic.predicate.at('my.blog_post.author_link', 'WNje3SUAAEGBu8bc'),
  ],
})

Filter by a field within a Group

To query by a field within a group, prepend the API ID of the field with the API ID of the group, as in: [my.[custom-type].[group].[field].

This example shows a query by a Content Relationship inside a Group, which is a useful use-case if you want to create your own tagging system (for example, to set "Authors" or "Categories" on each document).

Copy
client.getAllByType('blog_post', {
  predicates: [
    prismic.predicate.at(
      'my.blog_post.category_group.category_link',
      'WNje3SUAAEGBu8bc'
    ),
  ],
})

Query by a language

If you use more than one language in your repository, you'll need to query documents by language. If you don't specify a lang, the system will query the documents in your main language by default.

Copy
client.getAllByType('blog_post', { lang : 'fr-fr' })

Order results

Use an orderings object to sort your query results in a given order. The following example will sort blog posts by the date they were originally published, in descending order:

Copy
client.getAllByType('blog_post', {
  orderings: {
    field: 'document.first_publication_date',
    direction: 'desc',
  },
})

You can also specify an ordering by a field, or multiple fields:

Copy
client.getAllByType('product', {
  orderings: {
    field: 'my.product.price, my.product.title',
  },
})

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.