JSON:API

Use JSON:API for a standards-compliant way to interact with your Drupal content.

Fetching a Collection of Resources

To get a list of resources, make a GET request to the resource type's endpoint.

GET /jsonapi/node/article

Fetching a Single Resource

To get a single resource, append the resource's UUID to the URL.

GET /jsonapi/node/article/your-article-uuid

Filtering

You can filter resources based on their attributes. For example, to get all published articles:

GET /jsonapi/node/article?filter[status]=1

Sorting

To sort resources, use the `sort` query parameter. For example, to sort articles by title in ascending order:

GET /jsonapi/node/article?sort=title

To sort in descending order, prefix the field with a minus sign:

GET /jsonapi/node/article?sort=-title

Including Related Resources

You can include related resources in the response using the `include` query parameter. For example, to include the author of an article:

GET /jsonapi/node/article?include=field_author

Next.js Example

Here's how you can fetch and display articles in a Next.js page:

async function getArticles() {
  const res = await fetch(process.env.DRUPAL_JSONAPI_ENDPOINT + '/node/article?include=field_author', {
    next: { revalidate: 60 }
  });
  if (!res.ok) {
    throw new Error('Failed to fetch data')
  }
  const data = await res.json();
  return data;
}

export default async function ArticlesPage() {
  const { data: articles, included } = await getArticles();

  const getAuthor = (article) => {
    const authorRelationship = article.relationships.field_author.data;
    if (!authorRelationship) return null;
    return included.find(item => item.id === authorRelationship.id);
  };

  return (
    <div>
      <h1>Articles</h1>
      <ul>
        {articles.map((article: any) => {
          const author = getAuthor(article);
          return (
            <li key={article.id}>
              {article.attributes.title}
              {author && <span> by {author.attributes.name}</span>}
            </li>
          )
        })}
      </ul>
    </div>
  )
}