REST API Extensions
Registering Custom Endpoints
Extending the WordPress REST API allows you to expose custom data structures and application logic to external clients. All custom routes should be registered within the rest_api_init hook.
The Registration Pattern
To add a new endpoint, use the register_rest_route() function. It is recommended to use a unique namespace and versioning to prevent collisions.
add_action('rest_api_init', function () {
register_rest_route('custom/v1', '/data/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'get_custom_data_callback',
'permission_callback' => 'verify_endpoint_access',
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric($param);
}
),
),
));
});
Parameters & Arguments
| Parameter | Type | Description |
| :--- | :--- | :--- |
| methods | string | The HTTP verb (e.g., GET, POST, PUT, DELETE). |
| callback | callable | The function to execute when the endpoint is matched. |
| permission_callback | callable | A function that checks if the current user can access this endpoint. Must return boolean. |
| args | array | Configuration for input arguments, including validation and sanitization. |
Security and Authentication
Securing your custom endpoints is critical to protecting your application's data. WordPress provides two primary layers of security for REST extensions.
Permission Callbacks
Every endpoint must include a permission_callback. This determines if the requester has the necessary capabilities to view or modify the data.
/**
* Ensures only logged-in users with 'edit_posts' capability can access the route.
*/
function verify_endpoint_access(WP_REST_Request $request) {
return current_user_can('edit_posts');
}
Request Validation
Use the args array during registration to ensure that incoming data matches expected formats before the main callback logic is executed.
validate_callback: Returnstrueif the data is valid, or aWP_Errorif it is not.sanitize_callback: Cleans the input data before it reaches your callback function.
Handling Requests and Responses
The core of your API logic resides in the callback function, which interacts with the WP_REST_Request object and returns a WP_REST_Response.
Callback Implementation Example
The following example demonstrates how to retrieve data and return a standardized JSON response.
/**
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error on failure.
*/
function get_custom_data_callback($request) {
// Access URL parameters
$id = $request->get_param('id');
// Fetch your custom data
$data = get_custom_resource_by_id($id);
if (empty($data)) {
return new WP_Error('no_resource', 'Resource not found', array('status' => 404));
}
// Return a standard response object
return new WP_REST_Response($data, 200);
}
Standard Response Types
| Type | HTTP Status | Description |
| :--- | :--- | :--- |
| WP_REST_Response | 200 OK | Success; contains the requested data. |
| WP_REST_Response | 201 Created | Success; used for POST requests creating new items. |
| WP_Error | 401 Unauthorized | Returned when the permission_callback fails. |
| WP_Error | 404 Not Found | Returned when the requested resource ID does not exist. |
| WP_Error | 400 Bad Request | Returned when validate_callback fails. |
Internal Utilities
While the following are used internally to handle API logic, understanding their role is helpful for debugging:
WP_REST_Server: The main controller class that handles route matching and dispatching.rest_ensure_response(): An internal utility that ensures a return value is a properWP_REST_Responseobject. This is automatically applied to most callback returns but can be used manually if custom handling is required.