rest_do_request( WP_REST_Request|string $request )

Do a REST request.


Description Description

Used primarily to route internal requests through WP_REST_Server.


Parameters Parameters

$request

(WP_REST_Request|string) (Required) Request.


Top ↑

Return Return

(WP_REST_Response) REST response.


Top ↑

Source Source

File: wp-includes/rest-api.php

function rest_do_request( $request ) {
	$request = rest_ensure_request( $request );
	return rest_get_server()->dispatch( $request );
}

Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Ryan McCue

    rest_do_request can be used to internally send a REST API request and return the response object for it. You need to create the Request object first.

    $request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
    $response = rest_do_request( $request );
    
    if ( $response->is_error() ) {
    	// Convert to a WP_Error object.
    	$error = $response->as_error();
    	$message = $response->get_error_message();
    	$error_data = $response->get_error_data();
    	$status = isset( $error_data['status'] ) ? $error_data['status'] : 500;
    	wp_die( printf( '<p>An error occurred: %s (%d)</p>', $message, $error_data ) );
    }
    
    $data = $response->get_data();
    $headers = $response->get_headers();
    echo "<p>Success! Here's the data:</p>";
    var_dump( $data );
    

You must log in before being able to contribute a note or feedback.