Fetching Resources (GET)
How to fetch JSON:API resources using NextDrupal client.
The NextDrupal client ships with helpers to fetch JSON:API data from Drupal.
You can fetch a single resource, getResource or a collection of resources, getResourceCollection.
Every helper method:
- Accepts a resource type:
node--articleortaxonomy_term--tags. - A
paramsoption for query params:fields,include,filter, ...etc - A
withAuthoption for authentication. See the authentication docs. - A
deserializeoption if you want to fetch raw JSON:API data.
Here's what a call to fetch node--article resources would look like:
import { drupal } from "lib/drupal"
const articles = await drupal.getResourceCollection("node--article", { params: { "fields[node--article]": "title,created", // Fetch the title and created fields only. sort: "-created", // Sort the articles by created date in descending order. },})If you're building complex query params, see the guide on how to use Drupal JSON:API Params.
getResource
Fetch an article by id.
const article = await drupal.getResource( "node--article", "dad82fe9-f2b7-463e-8c5f-02f73018d6cb")Fetch a block by id.
const block = await drupal.getResource( "block_content--basic", "687f74ec-e599-4f5c-8175-f24510c77e83")See the API reference for getResource.
getResourceByPath
Fetch an article by path.
const article = await drupal.getResourceByPath("/blog/slug-for-article")See the API reference for getResourceByPath.
getResourceCollection
Fetch all users
const users = await drupal.getResourceCollection("user--user")Fetch all published articles sorted by date.
const articles = await drupal.getResourceCollection("node--article", { params: { "filter[status]": "1", sort: "-created", },})See the API reference for getResourceCollection.
getMenu
You need to install the JSON:API Menu Items module to use getMenu.
Fetch a menu by name
const menu = await drupal.getMenu("main")See the API reference for getMenu.
getView
You need to install the JSON:API Views module to use getView.
Fetch a view by name and display_id.
const view = await drupal.getView("promoted_items--block_1")See the API reference for getView.
getSearchIndex
You need to install the JSON:API Search API module to query your Search API indexes.
Fetch results from a Search API index.
const results = await drupal.getSearchIndex(indexName, { params: { filter: { name_of_field: value }, },})See the API reference for getSearchIndex.
Authentication
To make authenticated requests when fetching resources, use the withAuth option.
See the authentication docs for the supported authentication methods.
const article = await drupal.getResourceCollection( "node--article", { withAuth: // <-- Your auth method here. })