Menu
GraphQL API
Leverage the power of GraphQL to query your Drupal content with type safety and efficiency.
Querying a List of Resources
To get a list of resources, you can use a query like this:
query GetArticles {
nodeQuery(filter: {type: "article"}) {
entities {
... on NodeArticle {
title
body {
value
}
}
}
}
}
Querying a Single Resource
To get a single resource, you can use a query with an `id` variable:
query GetArticle($id: String!) {
node(id: $id) {
... on NodeArticle {
title
body {
value
}
}
}
}
Using a GraphQL Client
While you can use `fetch` to make GraphQL queries, a dedicated client like `graphql-request` can simplify things.
import { GraphQLClient, gql } from 'graphql-request'
const endpoint = process.env.DRUPAL_GRAPHQL_ENDPOINT || ''
const client = new GraphQLClient(endpoint)
const query = gql(/* GraphQL */ 'query GetArticles {
nodeQuery(filter: {type: "article"}) {
entities {
... on NodeArticle {
title
}
}
}
}')
const data = await client.request(query)
Next.js Example
Here's how you can fetch and display articles in a Next.js page using `graphql-request`:
import { GraphQLClient, gql } from 'graphql-request'
async function getArticles() {
const endpoint = process.env.DRUPAL_GRAPHQL_ENDPOINT || ''
const client = new GraphQLClient(endpoint)
const query = gql(/* GraphQL */ 'query GetArticles {
nodeQuery(filter: {type: "article"}) {
entities {
... on NodeArticle {
id
title
}
}
}
}')
const data = await client.request(query)
return data.nodeQuery.entities
}
export default async function ArticlesPage() {
const articles = await getArticles();
return (
<div>
<h1>Articles</h1>
<ul>
{articles.map((article: any) => (
<li key={article.id}>{article.title}</li>
))}
</ul>
</div>
)
}