Index of every page on this site: llms.txt
All skills
grasmash avatar

/drupal-api-endpoints

@19514f4
Run it yourself

Patterns for custom Drupal API endpoints that use UUIDs instead of sequential IDs: route, controller, and fetch templates, response-shape contracts for installed app clients, webhook handlers, authenticated cURL testing, and the JSON:API filter-access cache-poisoning fix. Use when creating custom routes, AJAX or JSON endpoints for a frontend or mobile app, webhook receivers, or JSON:API filters, and before adding an endpoint, to check whether an existing one already serves the need.

Use this Skill: https://skilld.dev/gh/grasmash/drupal-claude-skills/drupal-api-endpoints

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesjsonapi-filter-access.md

≈1.3k tokens on demand. Your agent reads this file only when SKILL.md points to it.

JSON:API Filter Access (Critical for Cache Poisoning Prevention)

The Problem

JSON:API endpoints that allow filtering entity collections require a specific hook implementation. Without it, Drupal's TemporaryQueryGuard denies all filter access, resulting in:

  • Empty responses ({"data":[], "meta":{"count":0}})
  • These empty responses get cached
  • All subsequent requests receive the cached empty response (cache poisoning)

Root Cause

The JSON:API module requires hook_jsonapi_ENTITY_TYPE_filter_access() to return an array keyed by JSONAPI_FILTER_AMONG_* constants.

If you return just AccessResult::neutral() or AccessResult::allowed() without the array structure, TemporaryQueryGuard interprets this as "no opinion" and adds WHERE 1 = 0 to queries.

Symptoms

  • JSON:API collection endpoints return {"data":[], "meta":{"count":0}}
  • Database has valid data
  • x-drupal-dynamic-cache: HIT header shows cached response
  • Cache clear temporarily fixes the issue
  • Issue returns after cache is repopulated

The Fix

Correct Implementation

/**
 * Implements hook_jsonapi_ENTITY_TYPE_filter_access() for ENTITY_TYPE.
 */
function mymodule_jsonapi_ENTITY_TYPE_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
  // Allow authenticated users to filter all entities
  if ($account->isAuthenticated()) {
    return [
      JSONAPI_FILTER_AMONG_ALL => AccessResult::allowed()
        ->cachePerPermissions()
        ->addCacheContexts(['user.roles:authenticated']),
    ];
  }

  // Deny anonymous users
  return [
    JSONAPI_FILTER_AMONG_ALL => AccessResult::forbidden()
      ->cachePerPermissions(),
  ];
}

WRONG Implementation (Causes Cache Poisoning)

// THIS CAUSES CACHE POISONING - DO NOT USE
function mymodule_jsonapi_ENTITY_TYPE_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
  return AccessResult::neutral()
    ->addCacheContexts(['url.query_args']);
}

Available Filter Subsets

The hook must return an array with one or more of these constants as keys:

Constant Description
JSONAPI_FILTER_AMONG_ALL All entities of the given type
JSONAPI_FILTER_AMONG_PUBLISHED Published entities only
JSONAPI_FILTER_AMONG_ENABLED Enabled entities only
JSONAPI_FILTER_AMONG_OWN Entities owned by the user

Real Example: Flagging Entities

From my_flag.module:

/**
 * Implements hook_jsonapi_ENTITY_TYPE_filter_access() for flagging.
 *
 * This hook controls whether users can filter flagging collections via JSON:API.
 * Without properly returning JSONAPI_FILTER_AMONG_* constants, the TemporaryQueryGuard
 * will add "WHERE 1 = 0" to queries, causing empty results that get cached and
 * served to all users (cache poisoning).
 */
function my_flag_jsonapi_flagging_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
  // Allow authenticated users to filter all flaggings
  if ($account->isAuthenticated()) {
    return [
      JSONAPI_FILTER_AMONG_ALL => AccessResult::allowed()
        ->cachePerPermissions()
        ->addCacheContexts(['user.roles:authenticated']),
    ];
  }

  // Anonymous users cannot filter flaggings
  return [
    JSONAPI_FILTER_AMONG_ALL => AccessResult::forbidden()
      ->cachePerPermissions(),
  ];
}

Debugging Cache Poisoning

Check if Response is Cached

curl -s -D - 'https://<project>.ddev.site/jsonapi/entity/bundle?filter[field]=value' \
  | grep -E "x-drupal-dynamic-cache|x-drupal-cache"
  • HIT = cached response (potentially poisoned)
  • MISS = fresh response
  • UNCACHEABLE = not cacheable

Verify Database Has Data

ddev drush sql:query "SELECT COUNT(*) FROM entity_table WHERE conditions"

Check What Hook Returns

ddev drush eval '
  $entity_type = \Drupal::entityTypeManager()->getDefinition("entity_type");
  $account = \Drupal::currentUser();
  $result = \Drupal::moduleHandler()->invokeAll("jsonapi_entity_type_filter_access", [$entity_type, $account]);
  print_r($result);
'

Cache Contexts for Filter Access

Always include appropriate cache contexts:

Context Use When
user.permissions Access varies by permission set
user.roles:authenticated Different for anon vs auth
user Different for each user (expensive!)
cachePerPermissions() Shorthand for permission-based caching

Related Issues

  • Drupal.org: #3376470 - JSON:API filtering returns empty despite permissions
  • Drupal.org: #3091824 - Flag module JSON:API integration
  • Drupal.org: #3091866 - Add FlaggingAccessControlHandler

Testing

After implementing the hook, test:

  1. Clear cache: ddev drush cr
  2. Make request as authenticated user
  3. Verify data returns
  4. Make second request, verify still returns data (from cache)
  5. Make request as anonymous, verify appropriate response
# Test as authenticated user
LOGIN_URL=$(ddev drush uli --uid=1 | head -1)
curl -c /tmp/cookies.txt -L -k "$LOGIN_URL" -o /dev/null
curl -b /tmp/cookies.txt -k 'https://<project>.ddev.site/jsonapi/flagging/follow?filter[entity_id]=123'

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts1mo3 checks · Risk SAFE
  • Gen Agent Trust Hub1mo

    The skill provides patterns and templates for creating Drupal API endpoints using best practices like UUIDs, access controls, and CSRF protection. It includes debugging commands for local development environments.

  • Socket1mo

    No alerts

  • Snyk1mo

    Risk: LOW · No issues

Signed by skilld at 19514f4. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 2 months ago

README badge

README badge for grasmash/drupal-claude-skills/drupal-api-endpoints