0

I'm trying to get a custom rest api working to handle some stuff. One part I need to do requires a Post/Put to the API.

But the API-call always goes 404 on me and I have no idea why. I've registered a test route as follows

register_rest_route('test/v1', 'test', array(
    'method' => WP_REST_Server::ALLMETHODS,
    'callback' => function () {
        return current_user_can("test_metadata_edit");
    },
    'permission_callback' => function () {
        return true;
    }
));

And I create a nonce for the Post/Put request via an inline script:

wp_add_inline_script("test_script", 'var nonce = "' . wp_create_nonce('wp_rest') . '"');

up until here everything works fine.

Now I try to GET the endpoint, which works. If I supply no nonce at all, it returns false. If a user is logged in and I use the generated nonce either via _wpnonce= or the X-WP-Nonce-header, it returns the correct result for the users capability. But if I try to Post, Put or Patch it always returns a 404 and I have absolutely no clue why. If I create a nonce for a logged out user though, I get a 403 instead.

fetch('/wp-json/test/v1/test', { method: 'GET', headers: {'X-WP-Nonce': '12345'}}) //works
fetch('/wp-json/test/v1/test?_wpnonce=12345', { method: 'GET'}}) //works
fetch('/wp-json/test/v1/test', { method: 'POST', headers: {'X-WP-Nonce': '12345'}) //does not work, 404
fetch('/wp-json/test/v1/test?_wpnonce=12345', { method: 'PUT' }) //also doesn't work, 404

Any ideas as to what is happening?

1 Answer 1

2

The 'method' argument for register_rest_route() should be named 'methods'. Because of the typo, the argument is interpreted as it's default value - 'GET' only.

2
  • This... is so unbelievable stupidly simple... But I didn't see it and probably wouldn't anytime soon. So thanks for sharper eyes than mine :D
    – CShark
    Jul 2, 2021 at 21:18
  • No problem :) . Doesn't help that the dev hub hasn't really documented the argument yet!
    – bosco
    Jul 3, 2021 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.