Fetch Data
This document will teach you how to connect to the API of your Prismic repository and how to create queries to retrieve documents.
This section will teach you how to connect to the API of your Prismic repository and how to create queries to retrieve documents.
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. createClient()
creates a client object with your repository name.
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.
import * as prismic from "@prismicio/client";
const repositoryName = "your-repository-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(repositoryName, {
routes,
accessToken,
});
From here you can start using client
to create queries like the following one that retrieves a document of the singleton type “home”:
const init = async () => {
client.getSingle("home");
};
init();
Putting it all together, all queries will happen inside the init function:
import * as prismic from "@prismicio/client";
const repositoryName = "your-repository-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(repositoryName, {
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
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.
client.getByUID(customType);
client.getByUID(customType, params);
For example, here we are querying for a page document with a UID of february-news
.
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.
client.getSingle(customType);
client.getSingle(customType, params);
For example, here we are querying for the only document of the custom type home
.
const prismicDoc = await client.getSingle("Home");
getFirst()
This method accepts an optional params object. It returns the first document that matches the search.
client.getFirst();
client.getFirst(params);
This example will return the most recent document from the repository:
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.
client.getAllByType(customType);
client.getAllByType(customType, params);
For example, here we are querying for all documents of the custom type blog_post
.
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.
client.getAllByIDs(arrayOfIDs);
client.getAllByIDs(arrayOfIDs, params);
In the following example returns the documents that match the given IDs.
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.
{
accessToken: "MC5ZVnRWUnhBQUFDWUE3N2tN.77...";
}
fetchLinks
Retrieves content from a linked document. Formatted as '[custom-type].[field]'
.
{
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.
{
lang: "fr-fr";
}
Learn more about the parameters object in the @prismicio/client Technical Reference.
filters
Filters are a way to refine your query. There are dozens of filters available with @prismicio/client
.
Most filters follow the following pattern: [q]
is a query filter, the path
is a string that specifies the field being examined, and value
specifies the value to evaluate against.
{
filters: [prismic.filter.[q](path, value)]
}
Here are some examples of the most commonly-used filters.
at()
filters for documents where the path matches a given value:
prismic.filter.at("my.product.category", "shoes");
not()
filters for documents where the path does not match a given value:
prismic.filter.not("my.product.category", "shoes");
any()
filters for documents where the path matches any value from an array:
prismic.filter.any("my.product.category", [
"shoes",
"jackets",
"blouses",
]);
Read the complete filters 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 filters 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 filters in a single query.
Here is a basic filter by field:
client.getAllByType("product", {
filters: [
prismic.filter.at("my.product.category", "shoes"),
],
});
Prismic also includes filters to filter by numbers and dates. This example will return all movies released in June 2022:
client.getAllByType("movie", {
filters: [
prismic.filter.month("my.movie.release-date", "June"),
prismic.filter.year("my.movie.release-date", 2022),
],
});
Filter by a content relationship
To query by a content relationship, use the ID of the linked document.
client.getAllByType("blog_post", {
filters: [
prismic.filter.at(
"my.blog_post.author_link",
"WNje3SUAAEGBu8bc",
),
],
});
Filter by a field within a repeatable group
To query by a field within a repeatable group, prepend the API ID of the field with the API ID of the repeatable 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).
client.getAllByType("blog_post", {
filters: [
prismic.filter.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.
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:
client.getAllByType("blog_post", {
orderings: {
field: "document.first_publication_date",
direction: "desc",
},
});
You can also specify an ordering by a field, or multiple fields:
client.getAllByType("product", {
orderings: {
field: "my.product.price, my.product.title",
},
});