You should have a nonce provided by your WP instance, and of course, being authenticated previously (through cookies, set by the wp-login normal process, a JWT, or even Basic authentication). This is because some requests are not approved if they come without the nonce
, in order to prevent abuse.
So, you could pass to your script a nonce generated from your backend, the example provided by the linked documentation is straightforward:
<?php
wp_localize_script( 'your-custom-id', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
Pay attention to the example provided, it is using jQuery, however the API doesn’t requires you to use it or even Backbone, in example I’m requesting the revisions of a post with Mithril like this:
m.request('/wp-json/wp/v2/posts/1/revisions', {
headers: {
'X-WP-Nonce': wpApiSettings.nonce
}
})
.then(revisions => console.log(revisions))
Requests without this header, to the default Controllers will respond with a status code of 401.