06

Drupal 11 APIs Reference Guide

A overview of Drupal 11's core APIs with descriptions and use cases.

Table of Contents

  1. Entity API
  2. Configuration API
  3. Form API
  4. Routing API
  5. Plugin API
  6. Services and Dependency Injection Container
  7. Database API
  8. Theme System and Render API
  9. Block API
  10. Cache API
  11. Ajax API
  12. Queue API
  13. State API
  14. Views API
  15. Field API
  16. Batch API
  17. Events System
  18. Migration API
  19. Typed Data API
  20. Menu and Links API
  21. Internationalization API
  22. Update API

Entity API

Description

The Entity API provides a unified way to work with different types of content and configuration in Drupal. Entities are objects that represent site data like nodes, users, taxonomy terms, and comments.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/group/entity_api/11.x

Why Use This API

  • Standardized Data Structure: All content follows the same patterns for CRUD operations
  • Fieldable: Entities can have custom fields attached without changing database schema
  • Translatable: Built-in support for multilingual content
  • Revisionable: Track changes over time with revision support
  • Access Control: Integrated permission system for viewing and editing
  • Storage Abstraction: Backend-agnostic storage layer

Common Use Cases

  • Creating custom content types (nodes)
  • Building user profiles with custom fields
  • Managing taxonomy vocabularies
  • Storing structured data with custom entity types

Configuration API

Description

The Configuration API manages site configuration separate from content. Configuration is stored in YAML files and can be version-controlled, imported, and exported between environments.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/config_api/11.x

Why Use This API

  • Version Control: Configuration lives in YAML files that can be committed to Git
  • Environment Management: Easily sync settings between dev, staging, and production
  • Type Safety: Configuration has schemas that define expected data types
  • Translatable: Configuration can be translated without modifying core files
  • Deployment-Friendly: Import/export configuration as part of deployment process

Common Use Cases

  • Storing module settings and configuration
  • Managing site settings that admins configure
  • Creating exportable configuration for distribution
  • Synchronizing settings across multiple environments

Form API

Description

The Form API provides a structured way to create, process, and validate forms in Drupal. Forms are defined as classes and rendered as structured arrays.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/form_api/11.x

Why Use This API

  • Security: Built-in CSRF protection and input validation
  • Consistency: All forms follow the same structure and behavior
  • Validation: Centralized validation with reusable validators
  • Ajax Support: Easy integration of Ajax functionality
  • State Management: Automatic handling of multi-step forms
  • Accessibility: Forms are accessible by default

Common Use Cases

  • Building admin configuration forms
  • Creating user input forms
  • Building complex multi-step wizards
  • Implementing Ajax-powered interactive forms

Routing API

Description

The Routing API defines how URLs map to controllers and content in Drupal. Routes are defined in YAML files and can have dynamic parameters, access control, and more.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Routing!routing.api.php/group/routing/11.x

Why Use This API

  • Clean URLs: Create human-readable and SEO-friendly URLs
  • Parameter Handling: Automatic conversion of URL parameters to objects
  • Access Control: Define permissions and access checks per route
  • HTTP Methods: Support for GET, POST, PUT, DELETE, etc.
  • Content Negotiation: Serve different formats (HTML, JSON, XML)

Common Use Cases

  • Creating custom pages and admin interfaces
  • Building REST API endpoints
  • Implementing custom callbacks and controllers
  • Creating dynamic routes with parameters

Plugin API

Description

The Plugin API provides a way to create swappable, discoverable components. Plugins are classes that implement a common interface and can be discovered using annotations, YAML, or hooks.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/plugin_api/11.x

Why Use This API

  • Extensibility: Allow other modules to extend functionality
  • Discoverability: Plugins are automatically discovered
  • Reusability: Share common behavior across different implementations
  • Derivatives: One plugin can provide multiple variations
  • Lazy Loading: Plugins are instantiated only when needed

Common Use Cases

  • Creating custom block types
  • Building field formatters and widgets
  • Implementing image effects and filters
  • Creating Views plugins
  • Developing custom search plugins

Services and Dependency Injection Container

Description

Services are reusable objects that perform specific tasks (database access, email sending, etc.). The Dependency Injection Container manages service instantiation and dependencies.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/container/11.x

Why Use This API

  • Decoupling: Services are loosely coupled and testable
  • Reusability: Services can be reused across the application
  • Testability: Easy to mock services in unit tests
  • Configuration: Services can be overridden or decorated
  • Performance: Services are lazy-loaded and can be shared

Common Use Cases

  • Accessing the database, logger, or cache
  • Sending emails or making HTTP requests
  • Working with configuration or state
  • Implementing business logic that needs to be reusable
  • Creating testable code with dependency injection

Database API

Description

The Database API provides a database abstraction layer that works across different database engines (MySQL, PostgreSQL, SQLite). It uses a query builder pattern for constructing SQL queries.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!database.api.php/group/database/11.x

Why Use This API

  • Database Portability: Code works across different database engines
  • Security: Built-in protection against SQL injection
  • Query Builder: Construct complex queries programmatically
  • Transactions: Support for database transactions
  • Schema API: Programmatically manage database schema

Common Use Cases

  • Querying custom database tables
  • Inserting, updating, or deleting records
  • Running complex queries with joins and conditions
  • Managing custom database schemas
  • Running database transactions

Theme System and Render API

Description

The Theme System controls how data is rendered into HTML. It uses Twig templates and render arrays to separate logic from presentation. The Render API provides a structured way to build renderable content.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/group/themeable/11.x

Why Use This API

  • Separation of Concerns: Logic is separated from presentation
  • Twig Templates: Secure, designer-friendly templating engine
  • Render Arrays: Structured data that can be altered before rendering
  • Caching: Automatic caching at the render level
  • Preprocessing: Modify variables before they reach templates
  • Theme Hooks: Override default templates and behavior

Common Use Cases

  • Creating custom Twig templates
  • Theming content types, blocks, and views
  • Building render arrays for custom output
  • Preprocessing variables for templates
  • Creating custom theme hooks

Block API

Description

The Block API allows you to create custom blocks that can be placed in regions throughout your site. Blocks are plugins that provide content for specific areas.

Official Documentation: https://api.drupal.org/api/drupal/core!modules!block!block.api.php/group/block_api/11.x

Why Use This API

  • Reusable Content: Create content that can be placed anywhere
  • Configuration: Blocks can have their own configuration forms
  • Visibility Control: Show/hide blocks based on conditions
  • Context-Aware: Blocks can vary by page, user, or other context
  • Pluggable: Other modules can provide block types

Common Use Cases

  • Creating custom sidebar content
  • Building configurable UI components
  • Displaying dynamic content in page regions
  • Creating reusable content widgets

Cache API

Description

The Cache API stores computed data to improve performance. It supports different cache bins, cache tags for invalidation, and multiple storage backends.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/cache/11.x

Why Use This API

  • Performance: Dramatically reduce expensive computations
  • Flexibility: Multiple cache bins for different data types
  • Cache Tags: Invalidate related cached items efficiently
  • Context: Cache can vary by user, permissions, language, etc.
  • Automatic Invalidation: Cache is cleared when dependencies change

Common Use Cases

  • Caching expensive database queries
  • Storing computed/processed data
  • Caching rendered content (pages, blocks)
  • Caching API responses
  • Storing discovery data (plugins, routes)

Ajax API

Description

The Ajax API allows you to update parts of a page without a full page refresh. It integrates with the Form API and provides commands for manipulating the DOM.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/ajax/11.x

Why Use This API

  • Better UX: Update content without page reloads
  • Form Integration: Easy Ajax integration in forms
  • Commands: Predefined commands for common operations
  • Progressive Enhancement: Works with and without JavaScript
  • Accessibility: Maintains accessibility with screen readers

Common Use Cases

  • Creating dynamic, interactive forms
  • Loading content without page refresh
  • Implementing auto-complete functionality
  • Building real-time interfaces
  • Updating parts of the page based on user actions

Queue API

Description

The Queue API allows you to defer processing of tasks to a later time. Items are added to queues and processed by workers, either during cron runs or via other triggers.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/queue/11.x

Why Use This API

  • Deferred Processing: Handle time-consuming tasks asynchronously
  • Reliability: Items are processed even if workers crash
  • Scalability: Process large numbers of items efficiently
  • Priority: Different queues can have different priorities
  • Backends: Support for database or custom queue backends

Common Use Cases

  • Processing large imports or exports
  • Sending bulk emails
  • Generating thumbnails or processing media
  • Performing API calls or external requests
  • Handling time-intensive operations

State API

Description

The State API stores temporary, environment-specific information that doesn't need to be in configuration or exported between environments.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/state_api/11.x

Why Use This API

  • Environment-Specific: Data stays in current environment
  • Performance: Faster than configuration for frequently-changed data
  • Simple: No schema or structure required
  • Non-Exportable: Intentionally excluded from configuration exports

Common Use Cases

  • Storing last cron run time
  • Tracking maintenance mode status
  • Saving temporary flags or counters
  • Caching dynamic, server-specific information
  • Storing system state that changes frequently

Views API

Description

The Views API allows you to create, modify, and programmatically interact with Views. Views are powerful tools for creating lists, tables, and displays of content.

Official Documentation: https://api.drupal.org/api/drupal/core!modules!views!views.api.php/group/views_overview/11.x

Why Use This API

  • Custom Displays: Create custom display plugins for Views
  • Field Handlers: Add custom field types to Views
  • Filters and Sorts: Implement custom filtering and sorting
  • Query Alteration: Modify Views queries programmatically
  • Extensibility: Extend Views with custom functionality

Common Use Cases

  • Creating custom Views field handlers
  • Building custom Views display plugins
  • Altering Views queries programmatically
  • Adding custom filters and sort criteria
  • Integrating custom data sources with Views

Field API

Description

The Field API provides a way to attach fields to entities. Fields are reusable components that can store different types of data (text, numbers, images, references, etc.).

Official Documentation: NA

Why Use This API

  • Reusable: Fields can be attached to any entity type
  • Pluggable: Create custom field types, widgets, and formatters
  • Storage: Field data is stored separately from entities
  • Translatable: Fields support multilingual content
  • Display Control: Separate widget and formatter configuration

Common Use Cases

  • Creating custom field types
  • Building custom field widgets (input forms)
  • Developing custom field formatters (display)
  • Attaching fields to custom entities
  • Processing field data programmatically

Batch API

Description

The Batch API allows you to process large datasets in chunks to avoid PHP timeouts and memory limits. It provides progress feedback and can run operations over multiple HTTP requests.

Official Documentation: https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/11.x

Why Use This API

  • Avoid Timeouts: Process large operations without hitting PHP limits
  • User Feedback: Show progress bar and status messages
  • Reliable: Operations continue even if interrupted
  • Memory Efficient: Process data in manageable chunks
  • Error Handling: Track and report errors during processing

Common Use Cases

  • Importing large datasets
  • Bulk updating content or users
  • Processing large files
  • Running database migrations
  • Generating reports on large datasets

Events System

Description

The Events System (Symfony EventDispatcher) allows modules to react to things happening in Drupal. Events are dispatched when actions occur, and subscribers can listen and respond.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/events/11.x

Why Use This API

  • Decoupled: Modules can react without tight coupling
  • Extensible: Multiple modules can respond to same event
  • Priority: Control the order of event subscriber execution
  • Flexible: More powerful than traditional hooks
  • Testable: Easy to test event dispatching and handling

Common Use Cases

  • Reacting to entity operations (save, delete, etc.)
  • Responding to configuration changes
  • Implementing custom business logic triggers
  • Integrating with external systems
  • Logging or tracking user actions

Migration API

Description

The Migration API provides a framework for importing content from external sources into Drupal. It supports various data sources and provides ETL (Extract, Transform, Load) capabilities.

Official Documentation: https://api.drupal.org/api/drupal/core!modules!migrate!migrate.api.php/group/migration/11.x

Why Use This API

  • Data Import: Import content from various sources (CSV, JSON, XML, databases)
  • Upgrade Path: Migrate from older Drupal versions
  • ETL Framework: Extract, transform, and load data systematically
  • Rollback: Ability to rollback migrations
  • Reusable: Migration configurations can be reused and shared

Common Use Cases

  • Migrating from Drupal 7 to Drupal 11
  • Importing content from external systems
  • Converting data formats
  • Bulk content creation from spreadsheets
  • Synchronizing data from external APIs

Typed Data API

Description

The Typed Data API provides a way to describe and interact with data in a type-safe manner. It defines data types and provides validation, transformation, and metadata.

Official Documentation: https://api.drupal.org/api/drupal/core!core.api.php/group/typed_data/11.x

Why Use This API

  • Type Safety: Define and enforce data types
  • Validation: Built-in validation for data types
  • Metadata: Attach metadata to data definitions
  • Constraints: Define custom validation constraints
  • Introspection: Programmatically inspect data structures

Common Use Cases

  • Defining custom data types
  • Implementing validation for complex data
  • Creating typed configuration
  • Building APIs with strict data types
  • Introspecting entity and field definitions

Menu and Links API

Description

The Menu and Links API manages menu items, local tasks (tabs), local actions (action buttons), and contextual links throughout Drupal.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Menu!menu.api.php/group/menu/11.x

Why Use This API

  • Navigation: Create structured navigation menus
  • User Interface: Tabs, action buttons, and contextual links
  • Dynamic: Menu items can be conditional based on permissions
  • Hierarchical: Support for nested menu structures
  • YAML Definition: Define menu items in YAML files

Common Use Cases

  • Creating admin menu items
  • Adding local tasks (tabs) to pages
  • Implementing action buttons
  • Building custom navigation menus
  • Adding contextual links to content

Internationalization API

Description

The Internationalization (i18n) API provides multilingual capabilities for Drupal. It allows content, configuration, and interface text to be translated into multiple languages.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Language!language.api.php/group/i18n/11.x

Why Use This API

  • Multilingual: Support for multiple languages out of the box
  • Translation Workflow: Built-in translation management
  • Language Context: Content can vary by language
  • Interface Translation: Translate UI strings and messages
  • Content Translation: Translate entities and fields

Common Use Cases

  • Building multilingual websites
  • Translating content types and fields
  • Localizing configuration and interface text
  • Creating language-specific variations
  • Implementing language switchers

Update API

Description

The Update API provides a way to run update scripts when modules are updated. These scripts handle database schema changes, data migrations, and configuration updates.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Extension!module.api.php/group/update_api/11.x

Why Use This API

  • Schema Updates: Modify database structure safely
  • Data Migration: Transform data during updates
  • Configuration Changes: Update configuration programmatically
  • Version Tracking: Track which updates have been run
  • Safe Deployment: Run updates as part of deployment process

Common Use Cases

  • Adding or modifying database tables
  • Updating entity schemas
  • Migrating data to new structures
  • Updating configuration after module changes
  • Performing cleanup operations

Additional Important APIs

Logging API (Watchdog)

Description: Log messages to Drupal's logging system for debugging and monitoring.

Official Documentation: https://www.drupal.org/docs/8/api/logging-api/overview

Why Use It: Track errors, warnings, and notices; monitor system behavior; debug issues; audit user actions.

Use Cases: Error logging, security auditing, debugging, monitoring system health.


Token API

Description: Provides placeholder tokens that can be replaced with dynamic values (like [node:title]).

Why Use It: Create dynamic content; build flexible templates; allow users to customize messages.

Use Cases: Email templates, custom strings, path aliases, configurable messages.


File API

Description: Manages file uploads, storage, and manipulation. Handles file entities and file system operations.

Official Documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!File!file.api.php/11.x

Why Use It: Secure file handling; file validation; managed file entities; stream wrapper support.

Use Cases: File uploads, image handling, document management, media libraries.


User API and Permissions

Description: Manages user accounts, roles, and permissions. Controls access to content and functionality.

Why Use It: User authentication; role-based access control; permission checks; user profile management.

Use Cases: Custom user registration, role management, permission checks, user authentication.


Mail API

Description: Send emails from Drupal using a pluggable mail system that supports different mail backends.

Why Use It: Templated emails; pluggable mail backends; email formatting; HTML email support.

Use Cases: Sending notifications, transactional emails, user communications, automated messages.


Language API

Description: Manage language settings and language negotiation for multilingual sites.

Why Use It: Language detection; language switching; multilingual routing; translation context.

Use Cases: Language switchers, content negotiation, language-specific URLs, multilingual sites.


Image API

Description: Process and manipulate images with image styles and effects.

Why Use It: Responsive images; automated image processing; image derivatives; effects pipeline.

Use Cases: Image resizing, thumbnails, image effects, responsive images, image optimization.


Search API

Description: Provides a framework for implementing search functionality with different search backends.

Why Use It: Extensible search; multiple search pages; custom search types; search plugins.

Use Cases: Site search, custom search pages, search indexing, faceted search integration.


Testing API

Description: Write automated tests for your code using PHPUnit, functional tests, and JavaScript tests.

Why Use It: Automated testing; continuous integration; regression prevention; code quality.

Use Cases: Unit tests, functional tests, browser tests, test-driven development.


Best Practices

General API Usage

  1. Use Dependency Injection: Always inject services rather than using static calls when possible
  2. Follow Coding Standards: Adhere to Drupal coding standards and PSR-12
  3. Use Type Hints: PHP 8+ type hints improve code quality and IDE support
  4. Cache Wisely: Cache expensive operations but use appropriate cache tags for invalidation
  5. Security First: Always validate input, sanitize output, and check permissions
  6. Use APIs, Not Direct SQL: Use Entity API and Database API instead of direct queries
  7. Document Your Code: Use PHPDoc comments for classes, methods, and complex logic
  8. Test Your Code: Write automated tests for critical functionality

Performance Considerations

  1. Use Lazy Loading: Services and plugins are lazy-loaded by default
  2. Implement Caching: Cache render arrays, entities, and expensive computations
  3. Use Cache Tags: Implement proper cache tag invalidation
  4. Batch Large Operations: Use Batch API or Queue API for large datasets
  5. Optimize Database Queries: Use proper indexes and avoid N+1 query problems
  6. Use BigPipe: For complex pages, consider BigPipe for progressive rendering

Security Best Practices

  1. Validate All Input: Use Form API validation and input filters
  2. Check Permissions: Always verify user access before displaying or processing data
  3. Sanitize Output: Use Twig's auto-escaping or proper sanitization functions
  4. Use CSRF Protection: Forms automatically include CSRF tokens
  5. Avoid SQL Injection: Use placeholders in database queries
  6. Secure File Uploads: Validate file types and use proper file handling

Resources

Official Documentation

  • Drupal API Documentation: https://api.drupal.org/api/drupal/11.x
  • Drupal.org Developer Guide: https://www.drupal.org/docs/develop
  • Drupal Coding Standards: https://project.pages.drupalcode.org/coding_standards/

Learning Resources

  • Examples Module: https://www.drupal.org/project/examples
  • API Change Records: https://www.drupal.org/list-changes/drupal
  • Symfony Documentation: https://symfony.com/doc (for services, events, routing)

Community Support

  • Drupal Slack: https://drupal.slack.com
  • Stack Exchange: https://drupal.stackexchange.com
  • Drupal Forums: https://www.drupal.org/forum

Quick Reference: When to Use Which API

Task API to Use
Store site configuration Configuration API
Create/read/update/delete content Entity API
Build a form Form API
Create a custom page Routing API + Controller
Make something pluggable Plugin API
Cache expensive operations Cache API
Query the database Database API or Entity Query
Create reusable functionality Services API
Add dynamic page updates Ajax API
Process large datasets Batch API or Queue API
Import external data Migration API
Create custom blocks Block API (Plugin)
Theme content Theme System + Twig
Store temporary data State API
React to system events Events System
Translate content Internationalization API
Send emails Mail API
Work with files File API
Create search functionality Search API

Conclusion

Drupal 11's API ecosystem provides a comprehensive, well-architected foundation for building powerful web applications. By understanding and properly utilizing these APIs, developers can create maintainable, secure, and performant websites that leverage Drupal's full capabilities.

Remember to always:

  • Follow Drupal coding standards
  • Use dependency injection
  • Implement proper caching
  • Validate input and check permissions
  • Write tests for your code
  • Consult the official API documentation

For the most up-to-date information, always refer to the official Drupal API documentation at https://api.drupal.org/api/drupal/11.x

Tags