WordPress.org

Make WordPress Core

Opened 6 weeks ago

Last modified 6 weeks ago

#49495 new defect (bug)

Undefined method WP_HTTP_Response::set_matched_route() called by dispatch() in WP_REST_Server class

Reported by: ali11007 Owned by:
Milestone: Future Release Priority: normal
Severity: normal Version: 4.4
Component: REST API Keywords: needs-patch
Focuses: docs, rest-api Cc:

Description

When registering new route for REST API using register_rest_route() and returning a WP_HTTP_Response object in defined callback, a fatal error occurs.

Steps to recreate error:
In a plugin: write this code:

<?php
add_action('rest_api_init', 'foo');
function foo()
{
  register_rest_route( 'namespace', '/route', array(
    'methods' => 'GET',
    'callback' => 'bar'
  ));
}
function bar($req)
{
  return new \WP_HTTP_Response();
}

the error is:

Fatal error: Uncaught Error:
Call to undefined method WP_HTTP_Response::set_matched_route() 
in /path/to/wordpress/wp-includes/rest-api/class-wp-rest-server.php:978

Change History (5)

#1 @swissspidy
6 weeks ago

  • Keywords close added

Custom REST API routes should return WP_REST_Response, not WP_HTTP_Response.

There's also a rest_ensure_response() helper function which wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned.

Refer to the documentation at https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/ and https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

#2 @ocean90
6 weeks ago

  • Focuses docs added
  • Keywords close removed

It's still odd that rest_ensure_response() returns a WP_HTTP_Response instance if such an object is passed. To me it looks like somebody thought that WP_HTTP_Response is an interface?

#3 @ali11007
6 weeks ago

in rest_ensure_response() there is:

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

I think it should be:

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

This ticket was mentioned in PR #166 on WordPress/wordpress-develop by ocean90.


6 weeks ago

Trac ticket: https://core.trac.wordpress.org/ticket/49495


An instance of WP_HTTP_Response doesn't ensure that the required methods by WP_REST_Server::dispatch() exists.

#5 @ocean90
6 weeks ago

  • Milestone changed from Awaiting Review to Future Release
  • Version changed from 5.3.2 to 4.4

There was an interface WP_HTTP_ResponseInterface which didn't get merged based on the committer reviews. See also this related commit about the @return docs. But at this time the interface didn't declare the required methods either.

https://github.com/WordPress/wordpress-develop/pull/166 is a possible fix for this.

Note: See TracTickets for help on using tickets.