REST API: No route was found matching the URL and request method

I’m having issues adding a custom REST API route to WordPress.
Using my own plugin, i’ve registered the route as followed:

add_action( 'rest_api_init', function() {
  register_rest_route( $namespace, 'handler_mijnenergie', array(
    'methods'   => '\WP_REST_Server::CREATABLE ',
    'callback'  => [ $this, 'handle_energie_data' ]
  ), false );
} );

When calling the namespace “/wp-json/watz/v1” I get a correct response in Postman that the route is shown.
enter image description here

However, when i try to access the route request directly, i get thrown a 404 error. So far I’ve tried:

  • Rewriting the permalinks
  • Using standard WordPress .htaccess
  • Disabling plugins
  • Changing method/namespace & request
  • Testing other plugin routes like Yoast or Contact Form 7 (they work)

Any idea what could be causing the issue here and what I need to alter to get this working?

1 Answer
1

It’s because of how you’ve defined the accepted methods:

'methods'   => '\WP_REST_Server::CREATABLE ',

You shouldn’t have quotes around it. WP_REST_Server::CREATABLE is a string that equals 'POST', but by putting quotes around it you’re literally setting the method as '\WP_REST_Server::CREATABLE', which is not a valid HTTP method. You can see this in the response to the namespace endpoint.

Set it like this:

'methods' => WP_REST_Server::CREATABLE

Or, if your file is using a PHP namespace, like this:

'methods' => \WP_REST_Server::CREATABLE

Or add this to the top of the file:

use WP_REST_Server;

Then make sure that when you’re accessing the route directly, that you’re using the correct method. If you’re using WP_REST_Server::CREATABLE then the endpoint will only respond to POST requests, so GET requests will return a 404, which includes when you access it via the browser.

Leave a Comment