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:

GraphQL Query
query GetArticles {
  nodeArticles(first: 10) {
    nodes {
      id
      title
      body {
        processed
      }
      path
    }
  }
}

Querying a Single Resource

To get a single resource, you can use a query with an `id` variable:

GraphQL Query
query GetArticle($id: ID!) {
  nodeArticle(id: $id) {
    id
    title
    body {
      processed
    }
    path
    created {
      timestamp
    }
  }
}

Using a GraphQL Client

While you can use `fetch` to make GraphQL queries, a dedicated client like `graphql-request` can simplify things.

lib/graphql.ts
import { GraphQLClient, gql } from 'graphql-request'

const endpoint = process.env.NEXT_PUBLIC_DRUPAL_BASE_URL + '/graphql'
const client = new GraphQLClient(endpoint)

const query = gql`
  query GetArticles {
    nodeArticles(first: 10) {
      nodes {
        id
        title
        path
      }
    }
  }
`

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`:

app/articles/page.tsx
import { GraphQLClient, gql } from 'graphql-request'

async function getArticles() {
  const endpoint = process.env.NEXT_PUBLIC_DRUPAL_BASE_URL + '/graphql'
  const client = new GraphQLClient(endpoint)

  const query = gql`
    query GetArticles {
      nodeArticles(first: 10) {
        nodes {
          id
          title
          path
        }
      }
    }
  `

  const data = await client.request(query)
  return data.nodeArticles.nodes
}

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>
  )
}