Getting Started with Headless Drupal: JSON:API Basics and Security Best Practices

Drupal has evolved beyond traditional CMS capabilities to become a powerful headless CMS solution. With JSON:API built into Drupal core, developers can easily expose structured content for modern frontends like React, Next.js, or even mobile apps. Today, we’ll explore how to consume Drupal content via JSON:API, define an API contract, and apply security best practices.


Why Headless Drupal?

Headless architecture decouples the frontend from the backend, allowing:

  • Flexibility: Use any frontend framework or mobile app.
  • Performance: Optimize rendering with SSR/ISR or static generation.
  • Scalability: Serve multiple channels from a single content source.

Step 1: Enable JSON:API

Drupal 8+ ships with JSON:API in core. Enable it:

Shell

drush en jsonapi jsonapi_extras


Show more lines

Base Endpoint

https://your-drupal-site.com/jsonapi

For a content type newspost:

https://your-drupal-site.com/jsonapi/node/newspost

Step 2: Define Your API Contract

An API contract ensures consistency between backend and frontend teams. Here’s what to include:

Endpoints

  • List newsposts:
    GET /jsonapi/node/newspost
  • Single newspost:
    GET /jsonapi/node/newspost/{uuid}

Query Parameters

  • Includes:
    ?include=uid,field_media_images,field_topc_category
  • Sparse Fields:
    fields[node--newspost]=title,body,field_reading_time
  • Filtering:
    filter[status]=1
  • Sorting:
    sort=-created
  • Pagination:
    page[limit]=10&page[offset]=0

Example URL

http://drupal11.docksal.site/jsonapi/node/newspost?fields[node--newspost]=title,body,field_reading_time&include=uid,field_media_images,field_topc_category

Step 3: Security Best Practices

Exposing APIs means securing them properly:

Disable Anonymous POST/PATCH

  • Go to People → Permissions and restrict content creation for anonymous users.

Basic Auth for Local Development
Enable:

Shell

drush en basic_auth
Show more lines

Use:

Shell

curl -u admin:password “https://your-drupal-site.com/jsonapi/node/newspost”
Show more lines

OAuth/OIDC for Production

  • Install OpenID Connect module.
  • Configure an identity provider (Keycloak, Azure AD, Okta).
  • Use Authorization: Bearer <token> for secure API calls.

CORS Configuration Add in settings.php:

PHP

$settings[‘cors.config’] = [

‘enabled’ => TRUE,

‘allowedHeaders’ => [‘Authorization’, ‘Content-Type’],

‘allowedMethods’ => [‘GET’, ‘POST’, ‘PATCH’, ‘DELETE’],

‘allowedOrigins’ => [‘https://your-frontend.com’],

‘supportsCredentials’ => TRUE,

];
Show more lines

Rate Limiting & CSRF

  • Use Flood Control or CDN-level rate limiting.
  • Enforce CSRF to

Leave a Comment