rest_ensure_response()WP 4.4.0

Checks and, if necessary, converts the passed data into an object of the WP_HTTP_Response class.

Used for stable code operation when creating responses in the REST API.

The function checks the passed data and, if needed, transforms it into a WP_REST_Response object. This object then allows the use of the set_status(), set_headers(), set_data(), and other methods.

If a WP_Error object or an instance of the WP_HTTP_Response class is passed, they will be returned as is without changes.

Through this function, WP automatically passes any data that is returned as a response in the REST API. For example, when the callback function register_rest_route() returns a string, this string is ultimately passed through this function.

No Hooks.

Returns

WP_REST_Response|WP_Error.

  • WP_Error, if a WP_Error object is passed as a parameter.
  • If the passed object is already an instance of the WP_HTTP_Response class, it does nothing and returns the passed object.
  • In all other cases, it creates a new WP_REST_Response object based on the passed data and returns its instance.

Usage

rest_ensure_response( $response );
$response(WP_Error/WP_HTTP_Response/misc) (required)
Response data that needs to be checked and possibly converted into a WP_HTTP_Response object.

Examples

1

#1 Getting the posts of the specified author

In WordPress, there are default methods for this purpose, but let's create our own simple version for example:

// registers the route
add_action( 'rest_api_init', function () {

	register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
		'methods'  => 'GET',
		'callback' => 'my_awesome_func',
	) );

} );

// Processes the request
function my_awesome_func( WP_REST_Request $request ) {

	$posts = get_posts( [
		'author' => (int) $request['id'],
	] );

	if ( empty( $posts ) ) {
		return new WP_Error('no_author_posts', 'No posts found', array( 'status' => 404 );
	}

	$response = rest_ensure_response( $posts );

	$response->set_status( 201 );
	$response->set_headers( [
		//'CONTENT_TYPE'   => 'application/x-www-form-urlencoded',
		//'CONTENT_LENGTH' => 105,
		'X_REAL_IP'      => '54.15.124.126',
	] );
	//$this->set_data( $data );

	return $response;
}

Changelog

Since 4.4.0 Introduced.

rest_ensure_response() code WP 6.9

function rest_ensure_response( $response ) {
	if ( is_wp_error( $response ) ) {
		return $response;
	}

	if ( $response instanceof WP_REST_Response ) {
		return $response;
	}

	/*
	 * While WP_HTTP_Response is the base class of WP_REST_Response, it doesn't provide
	 * all the required methods used in WP_REST_Server::dispatch().
	 */
	if ( $response instanceof WP_HTTP_Response ) {
		return new WP_REST_Response(
			$response->get_data(),
			$response->get_status(),
			$response->get_headers()
		);
	}

	return new WP_REST_Response( $response );
}