Getting started overview
Getting started with the Drupal API involves setting up a Drupal instance, configuring necessary modules for API exposure, and understanding the authentication methods available. Unlike many commercial APIs that provide a centralized developer portal for key generation, Drupal's API access is managed directly within each Drupal installation. This self-hosted model provides extensive control over API endpoints and security configurations.
The core Drupal API primarily exposes content entities (nodes, users, comments, taxonomy terms) and configuration entities (blocks, views) through RESTful web services. Developers can also extend these capabilities using contributed modules that provide additional API functionality, such as GraphQL or JSON:API endpoints. A foundational understanding of PHP and Drupal's module system is beneficial for advanced customization and troubleshooting.
This guide focuses on the initial steps to enable and interact with Drupal's built-in REST API. It outlines the process from setting up a local Drupal environment to making your first authenticated request.
Quick Reference Table
| Step | What to Do | Where |
|---|---|---|
| 1. Set up Drupal | Install a local or remote Drupal instance. | Drupal installation guide |
| 2. Enable Modules | Activate core RESTful Web Services and Serialization modules. | Drupal admin UI (/admin/modules) |
| 3. Configure Permissions | Grant API access permissions to roles. | Drupal admin UI (/admin/people/permissions) |
| 4. Create User | Set up a user account for API authentication. | Drupal admin UI (/admin/people/create) |
| 5. Authenticate | Choose an authentication method (e.g., Basic Auth, OAuth 2.0). | API request headers |
| 6. First Request | Send a GET request to a content endpoint. | cURL, Postman, or custom application |
Create an account and get keys
The concept of a centralized API key doesn't apply to Drupal in the same way it does to third-party services like Stripe API keys or Google Maps API keys. Instead, API access is controlled through user accounts and permissions within your specific Drupal installation. You will need to:
-
Install Drupal: If you don't have a Drupal site already, you'll need to install one. This can be on a local development environment (e.g., using Lando, DDEV, or Docker) or a remote server. Refer to the official Drupal installation guide for detailed instructions.
-
Enable Core Modules: Drupal's RESTful Web Services are provided by core modules that need to be enabled. Navigate to
Extend(/admin/modules) in your Drupal admin interface and enable the following modules:RESTful Web ServicesSerializationBasic Auth(for basic authentication)HAL(for Hypertext Application Language support, often used with REST)
After enabling, clear your caches (Drupal cache clearing documentation) to ensure the changes take effect.
-
Configure REST Resources: By default, not all resources are exposed via REST. You need to configure which resources are available and what methods (GET, POST, PATCH, DELETE) are allowed for each. This is typically done in
Configuration > Web services > REST UI(/admin/config/services/rest) if you have the contributed REST UI module installed. Alternatively, you can configure this programmatically viasettings.phpor a custom module.For example, to expose Node content:
- Enable the resource for
Content(entity:node). - Select the allowed methods (e.g., GET, POST).
- Choose the accepted formats (e.g.,
json,hal_json). - Select the authentication providers (e.g.,
basic_auth).
- Enable the resource for
-
Create an API User and Assign Permissions: You'll need a user account to authenticate API requests. Create a new user account via
People > Add user(/admin/people/create). Then, assign appropriate permissions to the role associated with this user (e.g., 'Authenticated user' or a custom 'API User' role). Navigate toPeople > Permissions(/admin/people/permissions) and grant permissions such as:Access RESTful web servicesView published content(for GET requests to nodes)Create [content type] content(for POST requests)Edit any [content type] content(for PATCH requests)Delete any [content type] content(for DELETE requests)
Your first request
After setting up your Drupal instance, enabling REST modules, and configuring permissions, you can make your first API request. This example uses Basic Authentication, which sends the username and password with each request. Ensure your connection is secured with HTTPS in production environments when using Basic Auth.
Example GET Request: Fetch Content
Let's fetch a list of articles. Assuming you have some article content on your Drupal site and the entity:node resource is configured for GET requests with basic_auth.
Endpoint: https://your-drupal-site.com/node/article?_format=json
Replace your-drupal-site.com with your actual Drupal site URL.
Using cURL:
curl -v -X GET \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
--user "YOUR_USERNAME:YOUR_PASSWORD" \
"https://your-drupal-site.com/node/article?_format=json"
Replace YOUR_USERNAME and YOUR_PASSWORD with the credentials of the API user you created.
Expected Response (truncated):
[
{
"nid": [
{
"value": 1
}
],
"uuid": [
{
"value": "a1b2c3d4-e5f6-7890-1234-567890abcdef"
}
],
"vid": [
{
"value": 1
}
],
"langcode": [
{
"value": "en"
}
],
"type": [
{
"target_id": "article",
"target_type": "node_type",
"target_uuid": "fedcba98-7654-3210-fedc-ba9876543210"
}
],
"title": [
{
"value": "My First Article"
}
],
"status": [
{
"value": true
}
],
"created": [
{
"value": "2023-01-01T12:00:00+00:00",
"format": "Y-m-d\TH:i:sP"
}
],
"changed": [
{
"value": "2023-01-01T12:00:00+00:00",
"format": "Y-m-d\TH:i:sP"
}
],
"promote": [
{
"value": true
}
],
"sticky": [
{
"value": false
}
]
}
// ... more articles
]
Example POST Request: Create Content
To create a new article, you would send a POST request. Ensure the entity:node resource is configured for POST requests and your API user has the Create article content permission.
Endpoint: https://your-drupal-site.com/node?_format=json
Using cURL:
curl -v -X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
--user "YOUR_USERNAME:YOUR_PASSWORD" \
-d '{
"_links": {
"type": {
"href": "https://your-drupal-site.com/rest/type/node/article"
}
},
"title": [
{
"value": "New Article from API"
}
],
"type": [
{
"target_id": "article"
}
],
"body": [
{
"value": "This is the body of the new article created via the Drupal API.",
"format": "full_html"
}
]
}' \
"https://your-drupal-site.com/node?_format=json"
Expected Response (truncated):
{
"nid": [
{
"value": 2
}
],
"uuid": [
{
"value": "f0e9d8c7-b6a5-4321-fedc-ba9876543210"
}
],
"vid": [
{
"value": 2
}
],
"langcode": [
{
"value": "en"
}
],
"type": [
{
"target_id": "article",
"target_type": "node_type",
"target_uuid": "fedcba98-7654-3210-fedc-ba9876543210"
}
],
"title": [
{
"value": "New Article from API"
}
],
"status": [
{
"value": true
}
]
// ... other fields
}
Common next steps
After successfully making your first API calls, consider these common next steps to further integrate with the Drupal API:
-
Explore Other Authentication Methods: While Basic Auth is simple for initial testing, consider more robust methods for production. Drupal supports OAuth 2.0 through the Simple OAuth module, which is a common standard for secure API access, as described by OAuth 2.0 documentation. Cookie-based authentication is also an option for same-domain applications.
-
Deepen REST Resource Configuration: Understand how to expose custom content types, fields, and configuration entities. The REST UI module simplifies this by providing a graphical interface to manage REST resources, formats, and authentication providers.
-
Learn about JSON:API: Drupal 8.7 and later ships with the JSON:API module in core. JSON:API is a specification for building APIs that minimizes the number of requests and the amount of data transferred between clients and servers. It offers a more standardized and often more efficient way to interact with Drupal entities compared to the generic REST module.
-
Implement GraphQL: For more complex data fetching requirements, consider using the GraphQL module. GraphQL allows clients to request exactly the data they need, reducing over-fetching and under-fetching issues common with traditional REST APIs. The GraphQL official documentation provides a comprehensive overview of its capabilities.
-
Develop Custom Endpoints: If the core REST or JSON:API capabilities do not meet specific requirements, you can create custom REST resources using Drupal's module development framework. This involves defining routes, controllers, and serialization logic within a custom module.
-
Client-side Integration: Integrate the API with a frontend framework (e.g., React, Vue, Angular) or a mobile application. Drupal's API makes it suitable for headless CMS architectures, where Drupal serves as a content repository and a separate application handles the user interface.
-
Security Best Practices: Always use HTTPS for all API communications. Implement robust authentication and authorization. Sanitize all input and validate all output to prevent common web vulnerabilities like SQL injection and cross-site scripting (XSS). Regularly update Drupal core and contributed modules to patch security vulnerabilities.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting steps:
-
401 Unauthorized:
- Incorrect Credentials: Double-check the username and password used in your Basic Auth header.
- Missing Permissions: Ensure the API user role has all necessary permissions (e.g.,
Access RESTful web services,View published content,Create article content). - Authentication Provider Not Enabled: Verify that
Basic Auth(or your chosen authentication provider) is enabled for the specific REST resource in/admin/config/services/rest.
-
403 Forbidden:
- Insufficient Permissions: Even if authenticated, the user might not have permission to perform the requested action (e.g., trying to delete content without the
Delete any contentpermission). - Resource Not Configured: The specific content type or entity you are trying to access might not be exposed via REST, or the requested method (GET, POST) is not enabled for it in
/admin/config/services/rest. - CSRF Token Missing (for POST/PATCH/DELETE): For authenticated requests that modify data, Drupal's REST API often requires a CSRF token to be sent in the
X-CSRF-Tokenheader. You can obtain this token by making a GET request to/session/token. This is particularly relevant when using cookie-based authentication or custom modules, though Basic Auth often bypasses it for simplicity.
- Insufficient Permissions: Even if authenticated, the user might not have permission to perform the requested action (e.g., trying to delete content without the
-
404 Not Found:
- Incorrect Endpoint URL: Verify the URL path (e.g.,
/node/article,/user). Ensure?_format=jsonor your desired format is appended. - Resource Not Enabled: The REST resource for the entity type (e.g.,
entity:node) might not be enabled in/admin/config/services/rest. - Clean URLs: Ensure clean URLs are enabled and your web server (Apache, Nginx) is correctly configured to rewrite URLs.
- Incorrect Endpoint URL: Verify the URL path (e.g.,
-
500 Internal Server Error:
- Check Drupal Logs: The most critical step. Navigate to
Reports > Recent log messages(/admin/reports/dblog) in your Drupal admin interface. Detailed error messages here will often pinpoint the exact issue, such as PHP errors, missing dependencies, or configuration problems. - PHP Configuration: Ensure your PHP installation meets Drupal's requirements and has necessary extensions enabled.
- Module Conflicts: Temporarily disable recently installed or updated modules to see if they are causing conflicts.
- Check Drupal Logs: The most critical step. Navigate to
-
No Response / Connection Refused:
- Firewall Issues: Check server firewalls or network configurations that might be blocking access to your Drupal site.
- Web Server Not Running: Ensure your web server (Apache, Nginx) and PHP-FPM (if used) are running.