Drupalwoo ☉

Build a custom Drupal route with a JSON endpoint

Drupal routes connect a URL to a controller, which makes them useful for focused, read-only features outside normal page rendering. Creating a custom Drupal route with a JSON response endpoint lets a JavaScript front end, mobile app, store system or monitoring service consume structured data. This guide targets Drupal 10 and 11 and uses Symfony’s JsonResponse through Drupal’s service container.

Australian commerce teams often ask for a “fair dinkum simple” endpoint: one that answers a narrow question without loading an entire catalogue. Imagine a Melbourne retailer using Drupal for editorial content and WooCommerce for purchasing, with its click-and-collect screen checking product availability before offering a pickup option.

Timing and dates deserve care down under. Sydney moves between AEST and AEDT, while Brisbane remains on AEST, so storing “AEST” as a fixed label can produce misleading data. Return an ISO 8601 timestamp with an offset, or UTC, and let the consumer convert it to the appropriate Australian local time.

The same endpoint can serve stores in Sydney, Melbourne and Brisbane without exposing customer records. Australian English spellings and unambiguous day-month-year dates help local teams, while the Australian Privacy Act and Australian Privacy Principles set firm boundaries around personal information. The implementation below keeps the public contract small, consistent and cache-friendly.

Configure the route and HTTP method

Start with routing.yml in a custom module. The route name must be unique across the site, while the path becomes the public URL. Restrict the method to GET because this endpoint only reads state; later, separate write routes should use POST, PATCH or DELETE with their own authentication rules.

site_status:
  path: '/api/site-status'
  defaults:
    _controller: '\Drupal\custom_status\Controller\SiteStatusController::status'
    _format: 'json'
  methods: [GET]
  requirements:
    _permission: 'access site status'

The _controller value identifies the PHP method that handles the request, and _format establishes JSON as the route format. The permission requirement causes Drupal to return 403 when the current user lacks access. Add the matching permission in permission.yml; otherwise, the requirement will never be granted.

Keep version prefixes such as /api/v1/ out of the path until a breaking response change is likely. Once clients depend on the contract, versioning can prevent an old application from breaking. A descriptive route name such as site_status is also easier to find with drush route:debug than a generic name such as api_1.

Return data through a controller

The controller builds the response and returns a Symfony JsonResponse, which encodes PHP arrays and sets the Content-Type header to application/json. Dependency injection keeps configuration access testable. This example injects Drupal’s configuration factory so the site name comes from configuration rather than being copied into code.

namespace Drupal\custom_status\Controller;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;

class SiteStatusController extends ControllerBase {
  public function __construct(
    protected ConfigFactoryInterface $configFactory,
  ) {}

  public function status(): JsonResponse {
    return new JsonResponse([
      'status' => 'ok',
      'site_name' => $this->configFactory->get('system.site')->get('name'),
      'generated_at' => (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format(DATE_ATOM),
    ]);
  }
}

Register the controller as a service and map the configuration factory explicitly:

services:
  Drupal\custom_status\Controller\SiteStatusController:
    arguments:
      $configFactory: '@config.factory'

The response keys form part of the endpoint contract, so rename them deliberately. JsonResponse handles JSON encoding, but it does not decide what data is safe to expose. Avoid returning the whole site configuration, database details, unpublished content or internal identifiers. Keep each payload focused on the consumer’s actual request.

Control access and route parameters

A route-level permission is the simplest access control. Define it in the module’s permission.yml, then grant it only to the roles that need the data:

permissions:
  'access site status':
    title: 'Access the site status endpoint'
    description: 'View operational data returned by the endpoint.'

For public operational data, Drupal’s _custom_access route requirement can apply a narrower rule, such as checking a token or application identity. Keep that logic in a dedicated access class rather than removing all route checks. Never accept a class name, service ID or arbitrary configuration key directly from the URL and pass it into the container.

Route parameters should be constrained in routing.yml. A stock endpoint might use path: '/api/stock/{sku}' with sku: '[A-Za-z0-9-]+'; the controller can then receive $sku as a method argument. Use strict character rules, validate the value in the controller and return a useful error when no record matches.

Separate authentication from authorisation: authentication establishes who the caller is, while authorisation decides whether that caller may use this route. Anonymous users can read a deliberately public health check, but authenticated requests should still be limited to the exact operation they need. Test anonymous, authorised and unauthorised calls before release.

Design predictable JSON errors

A successful payload is only half the contract. Clients also need predictable errors with the correct HTTP status code and a JSON body. Use 400 for malformed input, 401 for missing authentication, 403 for denied access, 404 for an unknown resource, 422 for valid but unusable data, 429 for rate limiting and 500 for an unexpected server failure.

Keep the error shape stable while making its message useful. For example, a stock controller can return:

return new JsonResponse([
  'error' => [
    'code' => 'unknown_sku',
    'message' => 'No stock record matched that SKU.',
  ],
], 404);

Catch expected business exceptions inside the controller and translate them into these responses. Let unexpected exceptions reach Drupal’s logging and exception handling, but do not expose stack traces, SQL queries, file paths or internal service names. A generic 500 payload can include a correlation ID that support staff can match against server logs.

Also consider how Drupal handles failures that occur before the controller runs, such as a malformed request or an access check error. If consumers require JSON for every response, add route-specific exception handling or an event subscriber that converts exceptions on the API path. Test the failure path; a tidy JSON success response does not guarantee a tidy JSON error response.

Test the endpoint in local development

Clear Drupal’s caches after installing or changing the module, then confirm that the route has been discovered. On a typical Drush setup, these commands are enough to begin checking it:

drush cr
drush route:debug | grep site_status
curl -i -H 'Accept: application/json' \
  https://dev.example.com.au/api/site-status

Check the response code, Content-Type header and decoded body. The request should return 200 with application/json, and the JSON should contain every documented key. Also try a missing permission, an unsupported method, an invalid route parameter and an unknown record. Each should produce the intended status and error shape rather than an HTML exception page.

Automated coverage should live in the module’s test suite. A Drupal functional test can request the URL, assert the status code, decode the JSON and verify important values. Add tests for access control and representative errors, then run them in CI with the same PHP version and database configuration used in production. That catches route-discovery and service-injection problems that a quick browser visit can miss.

Harden caching, CORS, and sensitive data

Caching can keep a national endpoint quick from Sydney to Brisbane, but only when the response is genuinely public. For a short-lived status feed, set explicit cache lifetimes instead of allowing intermediaries to apply unpredictable defaults:

$response = new JsonResponse($data);
$response->setPublic();
$response->setMaxAge(60);
$response->setSharedMaxAge(300);
return $response;

The browser cache and shared cache can have different lifetimes. Do not mark personalised or permission-restricted data as public. A CDN can reuse a public 200 response across users, so test cache keys and vary headers before release. For operational data that changes quickly, a short shared lifetime is usually safer than a long one.

CORS is a browser security mechanism, not an access-control system. If the JavaScript consumer is on another origin, allow that exact scheme, host and port, and do not combine a wildcard origin with credentialed requests. Read-only GET routes still need sensible access limits. Any future browser-based write operation requires authentication, appropriate CSRF protection where cookies are used, validation and an audit trail rather than relying on the route path alone.

Apply data minimisation under the Australian Privacy Act: collect only what the response needs, avoid stable customer identifiers and set retention rules for logs. Record endpoint latency, status codes and error codes without logging secrets or full payloads. These measures are particularly useful for a click-and-collect service expected to remain responsive during busy trading periods.

Deploy the endpoint and compare alternatives

Deploy the module code and its configuration through the normal release process. If routing.yml or permission.yml is exported to the site’s configuration directory, import it with drush config:import; otherwise, configuration management can silently replace the deployed definitions. A module installation or update hook can clear the necessary caches, while CI should rebuild a fresh Drupal site to verify that route discovery works from a clean state.

Treat the response as a published API contract. Record the route path, methods, authentication rules, status codes, field names and cache policy in the project’s documentation. Give payload changes a review process and consider versioning before renaming a field or changing its meaning. Monitor production logs and alert on rising 4xx or 5xx rates rather than waiting for a store’s front end to report a failure.

Not every data requirement needs a bespoke route. The usual choice depends on how much of Drupal’s content model and extension support you need:

Approach Best suited to Drupal setup Main trade-off
Custom route Small operational or calculated responses routing.yml and a controller You own validation, access and versioning
JSON:API Standard access to Drupal entities Enable the core JSON:API module Broad but follows entity and field conventions
Views-based export Curated lists built with a query builder Configure a Views display with a JSON output plugin Convenient, but plugin-dependent and less custom
Third-party REST resources Resource endpoints with established conventions Install and configure a REST resources module Mature tooling, but heavier than a small route

A custom route remains the neatest option for a narrow status response, while JSON:API is usually stronger when clients need nodes, taxonomy terms or users. For a review of the route, controller, tests and deployment details, talk to DrupalWoo and include the expected payload and hosting environment. The release record should then name the route, supported methods and cache policy.