Drupal Api

Published by thomasroger76 in drupal-skills

No known issues3 installs

What this skill does

Use when building headless or decoupled Drupal with JSON:API (filtering, includes, sparse fieldsets, pagination, mutations), setting up Simple OAuth for API authentication (client_credentials, authorization_code), configuring CORS for frontend applications, integrating with Next.js via the next-drupal module (preview mode, ISR, revalidation), implementing GraphQL with the graphql module, creating custom REST API resources (RestResource plugin), securing API endpoints with hook_jsonapi_entity_fil

Add Drupal Api to your agent

Review the source and files first. When you are ready, copy the prompt instruction or use the CLI command supported by your environment.

Install with a prompt

Paste this into a compatible coding agent:

add this skill "drupal-api" from https://github.com/thomasroger76/drupal-skills

Install with the CLI

Run this command in a controlled environment after reviewing the repository:

npx skills add https://github.com/thomasroger76/drupal-skills --skill drupal-api

Skill instructions

Drupal API / Headless — Référence Complète

Overview

Référentiel complet de Drupal en mode API-first / headless 8-11+ : JSON:API (core), Simple OAuth, CORS, Next.js + Drupal, GraphQL, REST Resources custom, webhooks pour invalidation de cache frontend, sécurisation des endpoints. Drupal est le CMS headless le plus puissant grâce à JSON:API en core depuis D8.7.

🎯 La Règle Fondamentale

JSON:API first. Avant de créer un endpoint custom (RestResource), vérifier que JSON:API ne suffit pas avec les filtres appropriés. JSON:API gère automatiquement la pagination, les includes, les permissions Drupal, et le cache.

Conventions transverses (ce repo)

  • Docker natif : toute commande Drupal est préfixée docker compose exec php (drush, composer, génération de clés). Jamais DDEV.
  • Plugins en attributs PHP (D10.2+/D11) : #[RestResource], #[QueueWorker], etc. Les annotations @RestResource/@QueueWorker sont dépréciées.
  • CORS par environnement : whitelist stricte, jamais * ni localhost en prod — piloter par getenv() / settings.local.php / config_split.
  • API custom versionnée : préfixe /api/v1/. Auth par OAuth2/Bearer, jamais de clé en paramètre d'URL.

JSON:API vs REST API vs GraphQL — Tableau Décisionnel

CritèreJSON:API (core)REST API (core)GraphQL (contrib)
DisponibilitéCore D8.7+Core D8Contrib
Requête flexible (champs à la demande)✅ sparse fieldsets❌✅
Filtrage avancé✅ filter[field][value]❌ limité✅
Includes (eager loading)✅ ?include=field❌✅
Mutations (POST/PATCH/DELETE)✅✅✅
Cache Drupal natif✅✅⚠️
AuthentificationOAuth / Cookie / BasicOAuth / Cookie / BasicOAuth / Cookie
Recommandé pourConsumer généralEndpoint spécifiqueFrontend complexe

Règle : utiliser JSON:API par défaut. REST Resource custom uniquement si besoin de logique métier non exposable via JSON:API. GraphQL pour les frontends avec besoins de requêtes très complexes.


Quick Decision Table

BesoinOutilRéférence
Lire des nœuds en JSON depuis un frontendGET /jsonapi/node/articlejsonapi-deep.md
Filtrer par champ (ex: status=published)?filter[status]=1jsonapi-deep.md
Filtrer avec opérateur (CONTAINS, IN, >=)?filter[title][operator]=CONTAINS&filter[title][value]=foojsonapi-deep.md
Filtres combinés (AND / OR)filter groups avec conjunctionjsonapi-deep.md
Inclure les entités référencées (eager load)?include=field_tags,field_imagejsonapi-deep.md
Limiter les champs retournés (sparse fieldsets)?fields[node--article]=title,bodyjsonapi-deep.md
Pagination JSON:API?page[limit]=10&page[offset]=20jsonapi-deep.md
Trier les résultats?sort=-created,titlejsonapi-deep.md
Créer/modifier un nœud via JSON:APIPOST/PATCH /jsonapi/node/article + token CSRFjsonapi-deep.md
Authentification machine-to-machineSimple OAuth — client_credentials grantauthentication.md
Authentification utilisateur frontendSimple OAuth — authorization_code + PKCEauthentication.md
Token JWT avec Simple OAuthdrupal/simple_oauth + drupal/jwtauthentication.md
Configurer CORS pour un frontendservices.yml → cors.config:cors-webhooks.md
Sécuriser l'accès à un bundle JSON:APIhook_jsonapi_entity_filter_access()jsonapi-deep.md
Masquer des champs de JSON:APIdrupal/jsonapi_extras — field overridejsonapi-deep.md
Aliaser les endpoints JSON:APIdrupal/jsonapi_extras — resource configjsonapi-deep.md
Frontend Next.js + DrupalModule drupal/next + next-drupal npmnextjs-drupal.md
Preview de brouillons dans Next.jsNext.js Preview Mode + Simple OAuthnextjs-drupal.md
Revalidation ISR après modificationWebhook Drupal → Next.js revalidatePathnextjs-drupal.md
GraphQL — requêtes flexiblesModule drupal/graphql v4graphql.md
Webhook sur modification de contenuhook_entity_presave / EventSubscriber + HTTP callcors-webhooks.md
Endpoint REST custom avec logique métierRestResource plugin customcors-webhooks.md
JSON:API pour contenu multilingue?filter[langcode]=fr + drupal-langcode headerjsonapi-deep.md
Performances JSON:API (cache)X-Drupal-Cache-Tags headers + Varnishjsonapi-deep.md
Rate limiting sur les endpoints JSON:APIdrupal/rate_limiter ou nginx limit_req_zone devant Drupalcors-webhooks.md
Exposer des Custom Entities via JSON:APIActiver JSON:API sur le type dans /admin/config/services/jsonapi + permissionsjsonapi-deep.md
API versioning sans casser les consumersJSON:API Extras — aliaser /jsonapi/node/article en /api/v1/articlesjsonapi-deep.md
Webhook avec validation de signature HMAChash_hmac('sha256', $payload, $secret) → vérifier le header X-Hub-Signature-256cors-webhooks.md
JSON:API + Decoupled Router (alias URL vers entité)drupal/decoupled_router → GET /router/translate-path?path=/mon-aliasnextjs-drupal.md
Pagination cursor-based (grands volumes)?page[cursor]=TOKEN avec drupal/jsonapi_cursor_paginatorjsonapi-deep.md

Anti-Patterns Critiques

❌ À ne jamais faire✅ Bonne pratiqueImpact
JSON:API sans authentification sur mutationsToujours simple_oauth ou session cookie pour POST/PATCH/DELETEN'importe qui peut modifier le contenu
CORS allowedOrigins: ['*'] en productionWhitelist des domaines frontend autorisésSécurité CORS inexistante
Exposer /jsonapi sans permissions DrupalConfigurer les permissions par bundleDonnées sensibles accessibles anonymement
Token OAuth hardcodé dans le code frontendVariables d'environnement + refresh tokenFuite de credentials
REST Resource custom pour ce que JSON:API faitUtiliser JSON:API avec filtres appropriésMaintenance inutile
GET /jsonapi/node/article sans page[limit]Toujours paginer — limiter à 50 maxRéponse de plusieurs MB, timeout
JSON:API sans drupal/jsonapi_extras pour les champs sensiblesMasquer les champs password, tokensExposition de données internes
Webhook sans validation de signatureHMAC-SHA256 sur le payloadN'importe qui peut déclencher le webhook
Next.js sans Preview Mode pour les brouillonsConfigurer drupal/next avec preview modeLes éditeurs ne voient pas leurs modifications
GraphQL sans persisted queries en prodActiver persisted queries + désactiver introspectionSchema exposé + queries arbitraires

Évolution par Version Majeure

FeatureD8D9D10D11
JSON:API (core)contrib✅ core D8.7+✅✅
REST API (core)✅✅✅✅
Simple OAuth (contrib)✅✅✅✅
GraphQL v4 (contrib)✅✅✅✅
drupal/next module❌✅✅✅
JSON:API mutations (POST/PATCH/DELETE)✅✅✅✅
drupal/jsonapi_extras✅✅✅✅
CORS core config✅✅✅✅
Decoupled Router (contrib)✅✅✅✅
Plugins REST/Queue en attribut PHP #[...]❌❌✅ D10.2+✅ (annotations dépréciées)

Auto-Amélioration

See Also

  • drupal-security — CSRF tokens pour mutations JSON:API, OAuth2, CORS
  • drupal-core — RestResource plugin, JSON:API accès, permissions
  • drupal-multilingual — JSON:API avec contenu traduit, Accept-Language header
  • drupal-performance — Cache JSON:API, X-Drupal-Cache-Tags, Varnish
  • drupal-config — Configuration JSON:API extras, Simple OAuth settings
  • drupal-migration — Importer du contenu via JSON:API, webhooks post-migration

Files included

  • authentication.md
  • CHANGELOG.md
  • cors-webhooks.md
  • graphql.md
  • jsonapi-deep.md
  • lessons.md
  • nextjs-drupal.md
  • SKILL.md

More skills

Drupal Api: Install, Source and Security | FunnelSlayer