Overview
WP_REST_Request
Request Properties
$request = new WP_REST_Request( 'GET', '/my-namespace/v1/examples' );
Method
Route
Headers
Parameters
URL Params
// Register our individual books endpoint. function prefix_register_book_route() { register_rest_route( 'my-namespace/v1', '/books/(?P<id>\d+)', array( // Supported methods for this endpoint. WP_REST_Server::READABLE translates to GET. 'methods' => WP_REST_Server::READABLE, // Register the callback for the endpoint. 'callback' => 'prefix_get_book', ) ); } add_action( 'rest_api_init', 'prefix_register_book_route' ); /** * Our registered endpoint callback. Notice how we are passing in $request as an argument. * By default, the WP_REST_Server will pass in the matched request object to our callback. * * @param WP_REST_Request $request The current matched request object. */ function prefix_get_book( $request ) { // Here we are accessing the path variable 'id' from the $request. $book = prefix_get_the_book( $request['id'] ); return rest_ensure_response( $book ); } // A simple function that grabs a book title from our books by ID. function prefix_get_the_book( $id ) { $books = array( 'Design Patterns', 'Clean Code', 'Refactoring', 'Structure and Interpretation of Computer Programs', ); $book = ''; if ( isset( $books[ $id ] ) ) { // Grab the matching book. $book = $books[ $id ]; } else { // Error handling. return new WP_Error( 'rest_not_found', esc_html__( 'The book does not exist', 'my-text-domain' ), array( 'status' => 404 ) ); } return $book; }
Query Params
Body Params
File Params
Attributes
{ "methods": { "GET": true }, "accept_json": false, "accept_raw": false, "show_in_index": true, "args": { "context": { "description": "Scope under which the request is made; determines fields present in response.", "type": "string", "sanitize_callback": "sanitize_key", "validate_callback": "rest_validate_request_arg", "enum": [ "view", "embed", "edit" ], "default": "view" }, "page": { "description": "Current page of the collection.", "type": "integer", "default": 1, "sanitize_callback": "absint", "validate_callback": "rest_validate_request_arg", "minimum": 1 }, "per_page": { "description": "Maximum number of items to be returned in result set.", "type": "integer", "default": 10, "minimum": 1, "maximum": 100, "sanitize_callback": "absint", "validate_callback": "rest_validate_request_arg" }, "search": { "description": "Limit results to those matching a string.", "type": "string", "sanitize_callback": "sanitize_text_field", "validate_callback": "rest_validate_request_arg" }, "after": { "description": "Limit response to resources published after a given ISO8601 compliant date.", "type": "string", "format": "date-time", "validate_callback": "rest_validate_request_arg" }, "author": { "description": "Limit result set to posts assigned to specific authors.", "type": "array", "default": [], "sanitize_callback": "wp_parse_id_list", "validate_callback": "rest_validate_request_arg" }, "author_exclude": { "description": "Ensure result set excludes posts assigned to specific authors.", "type": "array", "default": [], "sanitize_callback": "wp_parse_id_list", "validate_callback": "rest_validate_request_arg" }, "before": { "description": "Limit response to resources published before a given ISO8601 compliant date.", "type": "string", "format": "date-time", "validate_callback": "rest_validate_request_arg" }, "exclude": { "description": "Ensure result set excludes specific ids.", "type": "array", "default": [], "sanitize_callback": "wp_parse_id_list" }, "include": { "description": "Limit result set to specific ids.", "type": "array", "default": [], "sanitize_callback": "wp_parse_id_list" }, "offset": { "description": "Offset the result set by a specific number of items.", "type": "integer", "sanitize_callback": "absint", "validate_callback": "rest_validate_request_arg" }, "order": { "description": "Order sort attribute ascending or descending.", "type": "string", "default": "desc", "enum": [ "asc", "desc" ], "validate_callback": "rest_validate_request_arg" }, "orderby": { "description": "Sort collection by object attribute.", "type": "string", "default": "date", "enum": [ "date", "relevance", "id", "include", "title", "slug" ], "validate_callback": "rest_validate_request_arg" }, "slug": { "description": "Limit result set to posts with a specific slug.", "type": "string", "validate_callback": "rest_validate_request_arg" }, "status": { "default": "publish", "description": "Limit result set to posts assigned a specific status; can be comma-delimited list of status types.", "enum": [ "publish", "future", "draft", "pending", "private", "trash", "auto-draft", "inherit", "any" ], "sanitize_callback": "sanitize_key", "type": "string", "validate_callback": [ {}, "validate_user_can_query_private_statuses" ] }, "filter": { "description": "Use WP Query arguments to modify the response; private query vars require appropriate authorization." }, "categories": { "description": "Limit result set to all items that have the specified term assigned in the categories taxonomy.", "type": "array", "sanitize_callback": "wp_parse_id_list", "default": [] }, "tags": { "description": "Limit result set to all items that have the specified term assigned in the tags taxonomy.", "type": "array", "sanitize_callback": "wp_parse_id_list", "default": [] } }, "callback": [ {}, "get_items" ], "permission_callback": [ {}, "get_items_permissions_check" ] }
Internal Requests
// Register our mock batch endpoint. function prefix_register_batch_route() { register_rest_route( 'my-namespace/v1', '/batch', array( // Supported methods for this endpoint. WP_REST_Server::READABLE translates to GET. 'methods' => WP_REST_Server::READABLE, // Register the callback for the endpoint. 'callback' => 'prefix_do_batch_request', // Register args for the batch endpoint. 'args' => prefix_batch_request_parameters(), ) ); } add_action( 'rest_api_init', 'prefix_register_batch_route' ); /** * Our registered endpoint callback. Notice how we are passing in $request as an argument. * By default, the WP_REST_Server will pass in the matched request object to our callback. * * @param WP_REST_Request $request The current matched request object. */ function prefix_do_batch_request( $request ) { // Here we initialize the array that will hold our response data. $data = array(); $data = prefix_handle_batch_requests( $request['requests'] ); return $data; } /** * This handles the building of the response for the batch requests we make. * * @param array $requests An array of data to build WP_REST_Request objects from. * @return WP_REST_Response A collection of response data for batch endpoints. */ function prefix_handle_batch_requests( $requests ) { $data = array(); // Foreach request specified in the requests param run the endpoint. foreach ( $requests as $request_params ) { $response = prefix_handle_request( $request_params ); $key = $request_params['method'] . ' ' . $ request_params['route']; $data[ $key ] = prefix_prepare_for_collection( $response ); } return rest_ensure_response( $data ); } /** * This handles the building of the response for the batch requests we make. * * @param array $request_params Data to build a WP_REST_Request object from. * @return WP_REST_Response Response data for the request. */ function prefix_handle_request( $request_params ) { $request = new WP_REST_Request( $request_params['method'], $request_params['route'] ); // Add specified request parameters into the request. if ( isset( $request_params['params'] ) ) { foreach ( $request_params['params'] as $param_name => $param_value ) { $request->set_param( $param_name, $param_value ); } } $response = rest_do_request( $request ); return $response; } /** * Prepare a response for inserting into a collection of responses. * * This is lifted from WP_REST_Controller class in the WP REST API v2 plugin. * * @param WP_REST_Response $response Response object. * @return array Response data, ready for insertion into collection data. */ function prefix_prepare_for_collection( $response ) { if ( ! ( $response instanceof WP_REST_Response ) ) { return $response; } $data = (array) $response->get_data(); $server = rest_get_server(); if ( method_exists( $server, 'get_compact_response_links' ) ) { $links = call_user_func( array( $server, 'get_compact_response_links' ), $response ); } else { $links = call_user_func( array( $server, 'get_response_links' ), $response ); } if ( ! empty( $links ) ) { $data['_links'] = $links; } return $data; } /** * Returns the JSON schema data for our registered parameters. * * @return array $params A PHP representation of JSON Schema data. */ function prefix_batch_request_parameters() { $params = array(); $params['requests'] = array( 'description' => esc_html__( 'An array of request objects arguments that can be built into WP_REST_Request instances.', 'my-text-domain' ), 'type' => 'array', 'required' => true, 'validate_callback' => 'prefix_validate_requests', 'items' => array( array( 'type' => 'object', 'properties' => array( 'method' => array( 'description' => esc_html__( 'HTTP Method of the desired request.', 'my-text-domain' ), 'type' => 'string', 'required' => true, 'enum' => array( 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', ), ), 'route' => array( 'description' => esc_html__( 'Desired route for the request.', 'my-text-domain' ), 'required' => true, 'type' => 'string', 'format' => 'uri', ), 'params' => array( 'description' => esc_html__( 'Key value pairs of desired request parameters.', 'my-text-domain' ), 'type' => 'object', ), ), ), ), ); return $params; } function prefix_validate_requests( $requests, $request, $param_key ) { // If requests isn't an array of requests then we don't process the batch. if ( ! is_array( $requests ) ) { return new WP_Error( 'rest_invald_param', esc_html__( 'The requests parameter must be an array of requests.' ), array( 'status' => 400 ) ); } foreach ( $requests as $request ) { // If the method or route is not set then we do not run the requests. if ( ! isset( $request['method'] ) || ! isset( $request['route'] ) ) { return new WP_Error( 'rest_invald_param', esc_html__( 'You must specify the method and route for each request.' ), array( 'status' => 400 ) ); } if ( isset( $request['params'] ) && ! is_array( $request['params'] ) ) { return new WP_Error( 'rest_invald_param', esc_html__( 'You must specify the params for each request as an array of named key value pairs.' ), array( 'status' => 400 ) ); } } // This is a black listing approach to data validation. return true; }