REST API controllers with WP_REST_Controller
A plugin’s first REST route is usually a register_rest_route() call with a closure. By the fifth route, permission checks, argument definitions and response formatting are copied around, and ?_fields= or context=edit do not work like in core routes. Core’s own endpoints are built on WP_REST_Controller, and a plugin can extend the same class to get the same structure: one class per resource, a JSON schema, and the standard methods for list, read, create, update and delete.
Problem: A booking plugin has eight REST routes registered with closures. Each checks permissions differently, the responses have different shapes, and the block editor cannot use _fields to load only the needed fields.
Solution: Create a class that extends WP_REST_Controller, register its routes in register_routes(), implement get_items(), get_item() and create_item() with matching *_permissions_check() methods, describe the resource in get_item_schema(), and build responses with prepare_item_for_response() so that core handles field filtering and argument validation.
The controller
class Ha_Bookings_Controller extends WP_REST_Controller {
public function __construct() {
$this->namespace = 'ha/v1';
$this->rest_base = 'bookings';
}
public function register_routes(): void {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
),
'schema' => array( $this, 'get_public_item_schema' ),
) );
register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>\d+)', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
),
'schema' => array( $this, 'get_public_item_schema' ),
) );
}
public function get_items_permissions_check( $request ) {
return current_user_can( 'edit_posts' );
}
public function create_item_permissions_check( $request ) {
return current_user_can( 'edit_posts' );
}
public function get_items( $request ) {
$rows = ha_bookings_query( array(
'per_page' => $request['per_page'],
'page' => $request['page'],
'search' => $request['search'],
) );
$data = array();
foreach ( $rows['items'] as $row ) {
$data[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $row, $request ) );
}
$response = rest_ensure_response( $data );
$response->header( 'X-WP-Total', (string) $rows['total'] );
$response->header( 'X-WP-TotalPages', (string) ceil( $rows['total'] / $request['per_page'] ) );
return $response;
}
public function get_item( $request ) {
$row = ha_bookings_get( (int) $request['id'] );
if ( ! $row ) {
return new WP_Error( 'ha_booking_not_found', __( 'Booking not found.', 'textdomain' ), array( 'status' => 404 ) );
}
return $this->prepare_item_for_response( $row, $request );
}
public function create_item( $request ) {
$id = ha_bookings_insert( array(
'customer' => $request['customer'],
'date' => $request['date'],
) );
if ( is_wp_error( $id ) ) {
return $id;
}
$response = $this->prepare_item_for_response( ha_bookings_get( $id ), $request );
$response->set_status( 201 );
return $response;
}
public function prepare_item_for_response( $item, $request ) {
$data = array(
'id' => (int) $item->id,
'customer' => $item->customer,
'date' => mysql_to_rfc3339( $item->booked_for ),
);
$data = $this->filter_response_by_context( $data, $request['context'] ?? 'view' );
$data = $this->add_additional_fields_to_object( $data, $request );
return rest_ensure_response( $data );
}
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$this->schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'ha_booking',
'type' => 'object',
'properties' => array(
'id' => array( 'type' => 'integer', 'context' => array( 'view', 'edit' ), 'readonly' => true ),
'customer' => array( 'type' => 'string', 'context' => array( 'view', 'edit' ), 'required' => true, 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field' ) ),
'date' => array( 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), 'required' => true ),
),
);
return $this->add_additional_fields_schema( $this->schema );
}
}
add_action( 'rest_api_init', fn() => ( new Ha_Bookings_Controller() )->register_routes() );
ha_bookings_query() and the other ha_bookings_* functions stand for the plugin’s own data layer.
What the base class gives you
get_endpoint_args_for_item_schema()turns the schema into argument definitions:customeris required,datemust be a valid date-time, and core rejects invalid requests with a 400 beforecreate_item()runs.get_collection_params()addspage,per_page(max 100),searchandcontextwith validation._fieldsfiltering works automatically:/ha/v1/bookings?_fields=id,datereturns only these fields, becauserest_filter_response_fields()runs on every response.add_additional_fields_to_object()lets other plugins add fields withregister_rest_field( 'ha_booking', ... ), the object type being the schema title: register_rest_field.OPTIONS /wp-json/ha/v1/bookingsreturns the schema, which documents the API for its users.
NOTE: The *_permissions_check() methods are the place for capability checks, never the callback itself: core calls them before argument sanitizing and returns a proper 401 or 403. Simpler single routes with authentication and schema: custom REST API endpoints.