3 * REST API: WP_REST_Server class
11 * Core class used to implement the WordPress REST API server.
15 class WP_REST_Server {
18 * Alias for GET transport method.
23 const READABLE = 'GET';
26 * Alias for POST transport method.
31 const CREATABLE = 'POST';
34 * Alias for POST, PUT, PATCH transport methods together.
39 const EDITABLE = 'POST, PUT, PATCH';
42 * Alias for DELETE transport method.
47 const DELETABLE = 'DELETE';
50 * Alias for GET, POST, PUT, PATCH & DELETE transport methods together.
55 const ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE';
58 * Namespaces registered to the server.
64 protected $namespaces = array();
67 * Endpoints registered to the server.
73 protected $endpoints = array();
76 * Options defined for the routes.
82 protected $route_options = array();
85 * Instantiates the REST server.
90 public function __construct() {
91 $this->endpoints = array(
94 'callback' => array( $this, 'get_index' ),
107 * Checks the authentication headers if supplied.
112 * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful
113 * or no authentication provided
115 public function check_authentication() {
117 * Filters REST authentication errors.
119 * This is used to pass a WP_Error from an authentication method back to
122 * Authentication methods should check first if they're being used, as
123 * multiple authentication methods can be enabled on a site (cookies,
124 * HTTP basic auth, OAuth). If the authentication method hooked in is
125 * not actually being attempted, null should be returned to indicate
126 * another authentication method should check instead. Similarly,
127 * callbacks should ensure the value is `null` before checking for
130 * A WP_Error instance can be returned if an error occurs, and this should
131 * match the format used by API methods internally (that is, the `status`
132 * data should be used). A callback can return `true` to indicate that
133 * the authentication method was used, and it succeeded.
137 * @param WP_Error|null|bool WP_Error if authentication error, null if authentication
138 * method wasn't used, true if authentication succeeded.
140 return apply_filters( 'rest_authentication_errors', null );
144 * Converts an error to a response object.
146 * This iterates over all error codes and messages to change it into a flat
147 * array. This enables simpler client behaviour, as it is represented as a
148 * list in JSON rather than an object/map.
153 * @param WP_Error $error WP_Error instance.
154 * @return WP_REST_Response List of associative arrays with code and message keys.
156 protected function error_to_response( $error ) {
157 $error_data = $error->get_error_data();
159 if ( is_array( $error_data ) && isset( $error_data['status'] ) ) {
160 $status = $error_data['status'];
167 foreach ( (array) $error->errors as $code => $messages ) {
168 foreach ( (array) $messages as $message ) {
169 $errors[] = array( 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) );
174 if ( count( $errors ) > 1 ) {
175 // Remove the primary error.
176 array_shift( $errors );
177 $data['additional_errors'] = $errors;
180 $response = new WP_REST_Response( $data, $status );
186 * Retrieves an appropriate error representation in JSON.
188 * Note: This should only be used in WP_REST_Server::serve_request(), as it
189 * cannot handle WP_Error internally. All callbacks and other internal methods
190 * should instead return a WP_Error with the data set to an array that includes
191 * a 'status' key, with the value being the HTTP status to send.
196 * @param string $code WP_Error-style code.
197 * @param string $message Human-readable message.
198 * @param int $status Optional. HTTP status code to send. Default null.
199 * @return string JSON representation of the error
201 protected function json_error( $code, $message, $status = null ) {
203 $this->set_status( $status );
206 $error = compact( 'code', 'message' );
208 return wp_json_encode( $error );
212 * Handles serving an API request.
214 * Matches the current server URI to a route and runs the first matching
215 * callback then outputs a JSON representation of the returned value.
220 * @see WP_REST_Server::dispatch()
222 * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
224 * @return false|null Null if not served and a HEAD request, false otherwise.
226 public function serve_request( $path = null ) {
227 $content_type = isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json';
228 $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
229 $this->send_header( 'X-Robots-Tag', 'noindex' );
231 $api_root = get_rest_url();
232 if ( ! empty( $api_root ) ) {
233 $this->send_header( 'Link', '<' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"' );
237 * Mitigate possible JSONP Flash attacks.
239 * https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
241 $this->send_header( 'X-Content-Type-Options', 'nosniff' );
242 $this->send_header( 'Access-Control-Expose-Headers', 'X-WP-Total, X-WP-TotalPages' );
243 $this->send_header( 'Access-Control-Allow-Headers', 'Authorization, Content-Type' );
246 * Send nocache headers on authenticated requests.
250 * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
252 $send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
253 if ( $send_no_cache_headers ) {
254 foreach ( wp_get_nocache_headers() as $header => $header_value ) {
255 $this->send_header( $header, $header_value );
260 * Filters whether the REST API is enabled.
263 * @deprecated 4.7.0 Use the rest_authentication_errors filter to restrict access to the API
265 * @param bool $rest_enabled Whether the REST API is enabled. Default true.
267 apply_filters_deprecated( 'rest_enabled', array( true ), '4.7.0', 'rest_authentication_errors', __( 'The REST API can no longer be completely disabled, the rest_authentication_errors can be used to restrict access to the API, instead.' ) );
270 * Filters whether jsonp is enabled.
274 * @param bool $jsonp_enabled Whether jsonp is enabled. Default true.
276 $jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
278 $jsonp_callback = null;
280 if ( isset( $_GET['_jsonp'] ) ) {
281 if ( ! $jsonp_enabled ) {
282 echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
286 $jsonp_callback = $_GET['_jsonp'];
287 if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
288 echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 );
293 if ( empty( $path ) ) {
294 if ( isset( $_SERVER['PATH_INFO'] ) ) {
295 $path = $_SERVER['PATH_INFO'];
301 $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
303 $request->set_query_params( wp_unslash( $_GET ) );
304 $request->set_body_params( wp_unslash( $_POST ) );
305 $request->set_file_params( $_FILES );
306 $request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) );
307 $request->set_body( $this->get_raw_data() );
310 * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
311 * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
314 if ( isset( $_GET['_method'] ) ) {
315 $request->set_method( $_GET['_method'] );
316 } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
317 $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
320 $result = $this->check_authentication();
322 if ( ! is_wp_error( $result ) ) {
323 $result = $this->dispatch( $request );
326 // Normalize to either WP_Error or WP_REST_Response...
327 $result = rest_ensure_response( $result );
329 // ...then convert WP_Error across.
330 if ( is_wp_error( $result ) ) {
331 $result = $this->error_to_response( $result );
335 * Filters the API response.
337 * Allows modification of the response before returning.
340 * @since 4.5.0 Applied to embedded responses.
342 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
343 * @param WP_REST_Server $this Server instance.
344 * @param WP_REST_Request $request Request used to generate the response.
346 $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
348 // Wrap the response in an envelope if asked for.
349 if ( isset( $_GET['_envelope'] ) ) {
350 $result = $this->envelope_response( $result, isset( $_GET['_embed'] ) );
353 // Send extra data from response objects.
354 $headers = $result->get_headers();
355 $this->send_headers( $headers );
357 $code = $result->get_status();
358 $this->set_status( $code );
361 * Filters whether the request has already been served.
363 * Allow sending the request manually - by returning true, the API result
364 * will not be sent to the client.
368 * @param bool $served Whether the request has already been served.
370 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
371 * @param WP_REST_Request $request Request used to generate the response.
372 * @param WP_REST_Server $this Server instance.
374 $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
377 if ( 'HEAD' === $request->get_method() ) {
381 // Embed links inside the request.
382 $result = $this->response_to_data( $result, isset( $_GET['_embed'] ) );
384 $result = wp_json_encode( $result );
386 $json_error_message = $this->get_json_last_error();
387 if ( $json_error_message ) {
388 $json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, array( 'status' => 500 ) );
389 $result = $this->error_to_response( $json_error_obj );
390 $result = wp_json_encode( $result->data[0] );
393 if ( $jsonp_callback ) {
394 // Prepend '/**/' to mitigate possible JSONP Flash attacks.
395 // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
396 echo '/**/' . $jsonp_callback . '(' . $result . ')';
405 * Converts a response to data to send.
410 * @param WP_REST_Response $response Response object.
411 * @param bool $embed Whether links should be embedded.
413 * Data with sub-requests embedded.
415 * @type array [$_links] Links.
416 * @type array [$_embedded] Embeddeds.
419 public function response_to_data( $response, $embed ) {
420 $data = $response->get_data();
421 $links = $this->get_compact_response_links( $response );
423 if ( ! empty( $links ) ) {
424 // Convert links to part of the data.
425 $data['_links'] = $links;
428 // Determine if this is a numeric array.
429 if ( wp_is_numeric_array( $data ) ) {
430 $data = array_map( array( $this, 'embed_links' ), $data );
432 $data = $this->embed_links( $data );
440 * Retrieves links from a response.
442 * Extracts the links from a response into a structured hash, suitable for
449 * @param WP_REST_Response $response Response to extract links from.
450 * @return array Map of link relation to list of link hashes.
452 public static function get_response_links( $response ) {
453 $links = $response->get_links();
454 if ( empty( $links ) ) {
458 // Convert links to part of the data.
460 foreach ( $links as $rel => $items ) {
461 $data[ $rel ] = array();
463 foreach ( $items as $item ) {
464 $attributes = $item['attributes'];
465 $attributes['href'] = $item['href'];
466 $data[ $rel ][] = $attributes;
474 * Retrieves the CURIEs (compact URIs) used for relations.
476 * Extracts the links from a response into a structured hash, suitable for
483 * @param WP_REST_Response $response Response to extract links from.
484 * @return array Map of link relation to list of link hashes.
486 public static function get_compact_response_links( $response ) {
487 $links = self::get_response_links( $response );
489 if ( empty( $links ) ) {
493 $curies = $response->get_curies();
494 $used_curies = array();
496 foreach ( $links as $rel => $items ) {
498 // Convert $rel URIs to their compact versions if they exist.
499 foreach ( $curies as $curie ) {
500 $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
501 if ( strpos( $rel, $href_prefix ) !== 0 ) {
505 // Relation now changes from '$uri' to '$curie:$relation'.
506 $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
507 preg_match( '!' . $rel_regex . '!', $rel, $matches );
509 $new_rel = $curie['name'] . ':' . $matches[1];
510 $used_curies[ $curie['name'] ] = $curie;
511 $links[ $new_rel ] = $items;
512 unset( $links[ $rel ] );
518 // Push the curies onto the start of the links array.
519 if ( $used_curies ) {
520 $links['curies'] = array_values( $used_curies );
527 * Embeds the links from the data into the request.
532 * @param array $data Data from the request.
534 * Data with sub-requests embedded.
536 * @type array [$_links] Links.
537 * @type array [$_embedded] Embeddeds.
540 protected function embed_links( $data ) {
541 if ( empty( $data['_links'] ) ) {
547 foreach ( $data['_links'] as $rel => $links ) {
548 // Ignore links to self, for obvious reasons.
549 if ( 'self' === $rel ) {
555 foreach ( $links as $item ) {
556 // Determine if the link is embeddable.
557 if ( empty( $item['embeddable'] ) ) {
558 // Ensure we keep the same order.
563 // Run through our internal routing and serve.
564 $request = WP_REST_Request::from_url( $item['href'] );
570 // Embedded resources get passed context=embed.
571 if ( empty( $request['context'] ) ) {
572 $request['context'] = 'embed';
575 $response = $this->dispatch( $request );
577 /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
578 $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
580 $embeds[] = $this->response_to_data( $response, false );
583 // Determine if any real links were found.
584 $has_links = count( array_filter( $embeds ) );
587 $embedded[ $rel ] = $embeds;
591 if ( ! empty( $embedded ) ) {
592 $data['_embedded'] = $embedded;
599 * Wraps the response in an envelope.
601 * The enveloping technique is used to work around browser/client
602 * compatibility issues. Essentially, it converts the full HTTP response to
608 * @param WP_REST_Response $response Response object.
609 * @param bool $embed Whether links should be embedded.
610 * @return WP_REST_Response New response with wrapped data
612 public function envelope_response( $response, $embed ) {
614 'body' => $this->response_to_data( $response, $embed ),
615 'status' => $response->get_status(),
616 'headers' => $response->get_headers(),
620 * Filters the enveloped form of a response.
624 * @param array $envelope Envelope data.
625 * @param WP_REST_Response $response Original response data.
627 $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
629 // Ensure it's still a response and return.
630 return rest_ensure_response( $envelope );
634 * Registers a route to the server.
639 * @param string $namespace Namespace.
640 * @param string $route The REST route.
641 * @param array $route_args Route arguments.
642 * @param bool $override Optional. Whether the route should be overridden if it already exists.
645 public function register_route( $namespace, $route, $route_args, $override = false ) {
646 if ( ! isset( $this->namespaces[ $namespace ] ) ) {
647 $this->namespaces[ $namespace ] = array();
649 $this->register_route( $namespace, '/' . $namespace, array(
651 'methods' => self::READABLE,
652 'callback' => array( $this, 'get_namespace_index' ),
654 'namespace' => array(
655 'default' => $namespace,
665 // Associative to avoid double-registration.
666 $this->namespaces[ $namespace ][ $route ] = true;
667 $route_args['namespace'] = $namespace;
669 if ( $override || empty( $this->endpoints[ $route ] ) ) {
670 $this->endpoints[ $route ] = $route_args;
672 $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
677 * Retrieves the route map.
679 * The route map is an associative array with path regexes as the keys. The
680 * value is an indexed array with the callback function/method as the first
681 * item, and a bitmask of HTTP methods as the second item (see the class
684 * Each route can be mapped to more than one callback by using an array of
685 * the indexed arrays. This allows mapping e.g. GET requests to one callback
686 * and POST requests to another.
688 * Note that the path regexes (array keys) must have @ escaped, as this is
689 * used as the delimiter with preg_match()
694 * @return array `'/path/regex' => array( $callback, $bitmask )` or
695 * `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
697 public function get_routes() {
700 * Filters the array of available endpoints.
704 * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
705 * to an array of callbacks for the endpoint. These take the format
706 * `'/path/regex' => array( $callback, $bitmask )` or
707 * `'/path/regex' => array( array( $callback, $bitmask ).
709 $endpoints = apply_filters( 'rest_endpoints', $this->endpoints );
711 // Normalise the endpoints.
714 'accept_json' => false,
715 'accept_raw' => false,
716 'show_in_index' => true,
720 foreach ( $endpoints as $route => &$handlers ) {
722 if ( isset( $handlers['callback'] ) ) {
723 // Single endpoint, add one deeper.
724 $handlers = array( $handlers );
727 if ( ! isset( $this->route_options[ $route ] ) ) {
728 $this->route_options[ $route ] = array();
731 foreach ( $handlers as $key => &$handler ) {
733 if ( ! is_numeric( $key ) ) {
734 // Route option, move it to the options.
735 $this->route_options[ $route ][ $key ] = $handler;
736 unset( $handlers[ $key ] );
740 $handler = wp_parse_args( $handler, $defaults );
742 // Allow comma-separated HTTP methods.
743 if ( is_string( $handler['methods'] ) ) {
744 $methods = explode( ',', $handler['methods'] );
745 } elseif ( is_array( $handler['methods'] ) ) {
746 $methods = $handler['methods'];
751 $handler['methods'] = array();
753 foreach ( $methods as $method ) {
754 $method = strtoupper( trim( $method ) );
755 $handler['methods'][ $method ] = true;
764 * Retrieves namespaces registered on the server.
769 * @return array List of registered namespaces.
771 public function get_namespaces() {
772 return array_keys( $this->namespaces );
776 * Retrieves specified options for a route.
781 * @param string $route Route pattern to fetch options for.
782 * @return array|null Data as an associative array if found, or null if not found.
784 public function get_route_options( $route ) {
785 if ( ! isset( $this->route_options[ $route ] ) ) {
789 return $this->route_options[ $route ];
793 * Matches the request to a callback and call it.
798 * @param WP_REST_Request $request Request to attempt dispatching.
799 * @return WP_REST_Response Response returned by the callback.
801 public function dispatch( $request ) {
803 * Filters the pre-calculated result of a REST dispatch request.
805 * Allow hijacking the request before dispatching by returning a non-empty. The returned value
806 * will be used to serve the request instead.
810 * @param mixed $result Response to replace the requested version with. Can be anything
811 * a normal endpoint can return, or null to not hijack the request.
812 * @param WP_REST_Server $this Server instance.
813 * @param WP_REST_Request $request Request used to generate the response.
815 $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
817 if ( ! empty( $result ) ) {
821 $method = $request->get_method();
822 $path = $request->get_route();
824 foreach ( $this->get_routes() as $route => $handlers ) {
825 $match = preg_match( '@^' . $route . '$@i', $path, $args );
831 foreach ( $handlers as $handler ) {
832 $callback = $handler['callback'];
835 // Fallback to GET method if no HEAD method is registered.
836 $checked_method = $method;
837 if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
838 $checked_method = 'GET';
840 if ( empty( $handler['methods'][ $checked_method ] ) ) {
844 if ( ! is_callable( $callback ) ) {
845 $response = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) );
848 if ( ! is_wp_error( $response ) ) {
849 // Remove the redundant preg_match argument.
852 $request->set_url_params( $args );
853 $request->set_attributes( $handler );
857 foreach ( $handler['args'] as $arg => $options ) {
858 if ( isset( $options['default'] ) ) {
859 $defaults[ $arg ] = $options['default'];
863 $request->set_default_params( $defaults );
865 $check_required = $request->has_valid_params();
866 if ( is_wp_error( $check_required ) ) {
867 $response = $check_required;
869 $check_sanitized = $request->sanitize_params();
870 if ( is_wp_error( $check_sanitized ) ) {
871 $response = $check_sanitized;
877 * Filters the response before executing any REST API callbacks.
879 * Allows plugins to perform additional validation after a
880 * request is initialized and matched to a registered route,
881 * but before it is executed.
883 * Note that this filter will not be called for requests that
884 * fail to authenticate or match to a registered route.
888 * @param WP_HTTP_Response $response Result to send to the client. Usually a WP_REST_Response.
889 * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
890 * @param WP_REST_Request $request Request used to generate the response.
892 $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
894 if ( ! is_wp_error( $response ) ) {
895 // Check permission specified on the route.
896 if ( ! empty( $handler['permission_callback'] ) ) {
897 $permission = call_user_func( $handler['permission_callback'], $request );
899 if ( is_wp_error( $permission ) ) {
900 $response = $permission;
901 } elseif ( false === $permission || null === $permission ) {
902 $response = new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.' ), array( 'status' => 403 ) );
907 if ( ! is_wp_error( $response ) ) {
909 * Filters the REST dispatch request result.
911 * Allow plugins to override dispatching the request.
914 * @since 4.5.0 Added `$route` and `$handler` parameters.
916 * @param bool $dispatch_result Dispatch result, will be used if not empty.
917 * @param WP_REST_Request $request Request used to generate the response.
918 * @param string $route Route matched for the request.
919 * @param array $handler Route handler used for the request.
921 $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
923 // Allow plugins to halt the request via this filter.
924 if ( null !== $dispatch_result ) {
925 $response = $dispatch_result;
927 $response = call_user_func( $callback, $request );
932 * Filters the response immediately after executing any REST API
935 * Allows plugins to perform any needed cleanup, for example,
936 * to undo changes made during the {@see 'rest_request_before_callbacks'}
939 * Note that this filter will not be called for requests that
940 * fail to authenticate or match to a registered route.
942 * Note that an endpoint's `permission_callback` can still be
943 * called after this filter - see `rest_send_allow_header()`.
947 * @param WP_HTTP_Response $response Result to send to the client. Usually a WP_REST_Response.
948 * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
949 * @param WP_REST_Request $request Request used to generate the response.
951 $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
953 if ( is_wp_error( $response ) ) {
954 $response = $this->error_to_response( $response );
956 $response = rest_ensure_response( $response );
959 $response->set_matched_route( $route );
960 $response->set_matched_handler( $handler );
966 return $this->error_to_response( new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), array( 'status' => 404 ) ) );
970 * Returns if an error occurred during most recent JSON encode/decode.
972 * Strings to be translated will be in format like
973 * "Encoding error: Maximum stack depth exceeded".
978 * @return bool|string Boolean false or string error message.
980 protected function get_json_last_error() {
981 // See https://core.trac.wordpress.org/ticket/27799.
982 if ( ! function_exists( 'json_last_error' ) ) {
986 $last_error_code = json_last_error();
988 if ( ( defined( 'JSON_ERROR_NONE' ) && JSON_ERROR_NONE === $last_error_code ) || empty( $last_error_code ) ) {
992 return json_last_error_msg();
996 * Retrieves the site index.
998 * This endpoint describes the capabilities of the site.
1003 * @param array $request {
1006 * @type string $context Context.
1008 * @return array Index entity
1010 public function get_index( $request ) {
1011 // General site data.
1013 'name' => get_option( 'blogname' ),
1014 'description' => get_option( 'blogdescription' ),
1015 'url' => get_option( 'siteurl' ),
1016 'home' => home_url(),
1017 'namespaces' => array_keys( $this->namespaces ),
1018 'authentication' => array(),
1019 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
1022 $response = new WP_REST_Response( $available );
1024 $response->add_link( 'help', 'http://v2.wp-api.org/' );
1027 * Filters the API root index data.
1029 * This contains the data describing the API. This includes information
1030 * about supported authentication schemes, supported namespaces, routes
1031 * available on the API, and a small amount of data about the site.
1035 * @param WP_REST_Response $response Response data.
1037 return apply_filters( 'rest_index', $response );
1041 * Retrieves the index for a namespace.
1046 * @param WP_REST_Request $request REST request instance.
1047 * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
1048 * WP_Error if the namespace isn't set.
1050 public function get_namespace_index( $request ) {
1051 $namespace = $request['namespace'];
1053 if ( ! isset( $this->namespaces[ $namespace ] ) ) {
1054 return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) );
1057 $routes = $this->namespaces[ $namespace ];
1058 $endpoints = array_intersect_key( $this->get_routes(), $routes );
1061 'namespace' => $namespace,
1062 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ),
1064 $response = rest_ensure_response( $data );
1066 // Link to the root index.
1067 $response->add_link( 'up', rest_url( '/' ) );
1070 * Filters the namespace index data.
1072 * This typically is just the route data for the namespace, but you can
1073 * add any data you'd like here.
1077 * @param WP_REST_Response $response Response data.
1078 * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
1080 return apply_filters( 'rest_namespace_index', $response, $request );
1084 * Retrieves the publicly-visible data for routes.
1089 * @param array $routes Routes to get data for.
1090 * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
1091 * @return array Route data to expose in indexes.
1093 public function get_data_for_routes( $routes, $context = 'view' ) {
1094 $available = array();
1096 // Find the available routes.
1097 foreach ( $routes as $route => $callbacks ) {
1098 $data = $this->get_data_for_route( $route, $callbacks, $context );
1099 if ( empty( $data ) ) {
1104 * Filters the REST endpoint data.
1108 * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
1110 $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
1114 * Filters the publicly-visible data for routes.
1116 * This data is exposed on indexes and can be used by clients or
1117 * developers to investigate the site and find out how to use it. It
1118 * acts as a form of self-documentation.
1122 * @param array $available Map of route to route data.
1123 * @param array $routes Internal route data as an associative array.
1125 return apply_filters( 'rest_route_data', $available, $routes );
1129 * Retrieves publicly-visible data for the route.
1134 * @param string $route Route to get data for.
1135 * @param array $callbacks Callbacks to convert to data.
1136 * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
1137 * @return array|null Data for the route, or null if no publicly-visible data.
1139 public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
1142 'methods' => array(),
1143 'endpoints' => array(),
1146 if ( isset( $this->route_options[ $route ] ) ) {
1147 $options = $this->route_options[ $route ];
1149 if ( isset( $options['namespace'] ) ) {
1150 $data['namespace'] = $options['namespace'];
1153 if ( isset( $options['schema'] ) && 'help' === $context ) {
1154 $data['schema'] = call_user_func( $options['schema'] );
1158 $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
1160 foreach ( $callbacks as $callback ) {
1161 // Skip to the next route if any callback is hidden.
1162 if ( empty( $callback['show_in_index'] ) ) {
1166 $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
1167 $endpoint_data = array(
1168 'methods' => array_keys( $callback['methods'] ),
1171 if ( isset( $callback['args'] ) ) {
1172 $endpoint_data['args'] = array();
1173 foreach ( $callback['args'] as $key => $opts ) {
1175 'required' => ! empty( $opts['required'] ),
1177 if ( isset( $opts['default'] ) ) {
1178 $arg_data['default'] = $opts['default'];
1180 if ( isset( $opts['enum'] ) ) {
1181 $arg_data['enum'] = $opts['enum'];
1183 if ( isset( $opts['description'] ) ) {
1184 $arg_data['description'] = $opts['description'];
1186 if ( isset( $opts['type'] ) ) {
1187 $arg_data['type'] = $opts['type'];
1189 if ( isset( $opts['items'] ) ) {
1190 $arg_data['items'] = $opts['items'];
1192 $endpoint_data['args'][ $key ] = $arg_data;
1196 $data['endpoints'][] = $endpoint_data;
1198 // For non-variable routes, generate links.
1199 if ( strpos( $route, '{' ) === false ) {
1200 $data['_links'] = array(
1201 'self' => rest_url( $route ),
1206 if ( empty( $data['methods'] ) ) {
1207 // No methods supported, hide the route.
1215 * Sends an HTTP status code.
1220 * @param int $code HTTP status.
1222 protected function set_status( $code ) {
1223 status_header( $code );
1227 * Sends an HTTP header.
1232 * @param string $key Header key.
1233 * @param string $value Header value.
1235 public function send_header( $key, $value ) {
1237 * Sanitize as per RFC2616 (Section 4.2):
1239 * Any LWS that occurs between field-content MAY be replaced with a
1240 * single SP before interpreting the field value or forwarding the
1241 * message downstream.
1243 $value = preg_replace( '/\s+/', ' ', $value );
1244 header( sprintf( '%s: %s', $key, $value ) );
1248 * Sends multiple HTTP headers.
1253 * @param array $headers Map of header name to header value.
1255 public function send_headers( $headers ) {
1256 foreach ( $headers as $key => $value ) {
1257 $this->send_header( $key, $value );
1262 * Retrieves the raw request entity (body).
1267 * @global string $HTTP_RAW_POST_DATA Raw post data.
1269 * @return string Raw request data.
1271 public static function get_raw_data() {
1272 global $HTTP_RAW_POST_DATA;
1275 * A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
1276 * but we can do it ourself.
1278 if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
1279 $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
1282 return $HTTP_RAW_POST_DATA;
1286 * Extracts headers from a PHP-style $_SERVER array.
1291 * @param array $server Associative array similar to `$_SERVER`.
1292 * @return array Headers extracted from the input.
1294 public function get_headers( $server ) {
1297 // CONTENT_* headers are not prefixed with HTTP_.
1298 $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true );
1300 foreach ( $server as $key => $value ) {
1301 if ( strpos( $key, 'HTTP_' ) === 0 ) {
1302 $headers[ substr( $key, 5 ) ] = $value;
1303 } elseif ( isset( $additional[ $key ] ) ) {
1304 $headers[ $key ] = $value;