I have a custom endpoint which does nothing but return a test string. I can reach that endpoint by navigating to mydomain.com/wp-json/mytools/v1/method/get_user_data
and it correctly returns my test string, but, I want to be able to reach that endpoint using Javascript, and, I read that the wp-api handles authentication automatically so I should be able to get a current logged in user with this method.
What I need is to be able to use something like wp.api.mytools.method.get_current_user
and get the information for the currently logged in user. Is this even possible?
This is the way I created the endpoint:
register_rest_route( 'mytools/v1', '/method/(?P<method>[\w]+)', array(
'methods' => 'GET',
'callback' => 'invoke_method',
));
And this is the invoke_method
function:
function invoke_method( WP_REST_Request $request ) {
return wp_get_current_user();
}
This functionality is already implemented by WordPress at the WP_REST endpoint '.../wp-json/wp/v2/users/me. In addition to the logged-in cookie WP REST authentication requires a nonce specified by a query argument '_wpnonce'. The value of this nonce is generated by calling wp_create_nonce( 'wp_rest' ). A normal WordPress front-end page will include the script .../wp-includes/js/api-request.js. This script will define a global wpApiSettings.nonce which will contain this nonce so you can use the request '.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce. So, you can use jQuery.get().
jQuery.get(
'.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce,
function( response ) {
var userData = JSON.parse( response );
) }
);
If you only want to get the current user I don't think you need Backbone.js. Backbone.js will synchronise collections and models using CRUD and you are not doing any of this.