8

Recently all of my REST-API requests suddenly turned to return a 404 error, Every request (no matter custom endpoint or built-in).

Then I figured it's because of permalink's structure. /wp-json/ is not accessible under plain permalink, since there is simply no redirect rule available at the moment.

Is it possible to use the REST endpoints in this situation? Both custom and built-in.

15

Yes you can. Just add the rest_route query parameter.

So

https://wordpress.org/wp-json/

would become

https://wordpress.org/?rest_route=/

Or https://wordpress.org/wp-json/wp/v2/ would become https://wordpress.org/?rest_route=/wp/v2 to give you a more complete example.

So you're wondering how to decide which one to use? Worry no more, there's a function for that: get_rest_url()

Another option is the fact that by default there is a <link> in the header that gives you the API root.

<link rel='https://api.w.org/' href='https://wordpress.org/wp-json/' />

So in case you need to figure that out from client side JS just use something along the lines of

document.querySelectorAll('link[rel="https://api.w.org/"]')[0].getAttribute('href');

So basically you shouldn't take the wp-json part as given (and hardcode it) but always build it dynamically either using get_rest_url() or the JS approach mentioned above.

  • So, if I want to use it in plain, it would be something like https://wordpress.org/?rest_route=SOMEPATH&value1=X&value2=Y? This means I need to have a conditional to detect the permalink structure and change the REST route based on that? – Jack Johansson Jul 12 '17 at 15:11
  • Well maybe not a conditional but you need to build it dynamically. See edits above. – kraftner Jul 12 '17 at 15:20
  • how would you use this route with jsonp? I tried /?rest_route=/?_jsonp=callBackfn but get a 404 status. – redshift Aug 31 '17 at 15:28
  • @redshift Usually please open a separate question for things like these. In your case you should read up on query string delimiters en.wikipedia.org/wiki/Query_string#Structure You'd need to write it like this /?rest_route=/&_jsonp=callBackfn – kraftner Sep 13 '17 at 12:07
1

You could add one rewrite on your web server.

E.g for nginx

location ~ ^/wp-json/ {
    rewrite ^/wp-json/(.*?)$ /?rest_route=/$1 last;
}
0

The rest_route query parameter is the Ugly (Wordpress's choice of words not mine) style of Permalink. You can change the permilink style to Post name as illustrated in the screen shot below and the wp-json route should beomce accessable in the URL. It is possible that other of these permilink styles will work, but Post name worked for me and I didn't explore beyond that

Picture illustrating button clicks required to change settings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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