You don't need to login into your WordPress Dashboard before consuming the WordPress REST API from an external app; it's irrelevant (unless of course you want to rely on cookies as you are developing).
It is important to note that you may already have your Cross-Origin Resource Sharing (CORS) enabled on your server side unless you are consuming from the same origin or same server.
The HTTP response header 401 you had indicates an that an unauthorized request has been sent for processing and your response likely would have been:
{
"code": "rest_cannot_edit",
"message": "Sorry, you are not allowed to edit this post.",
"data": {
"status": 401
}
}
In other words, you are either not logged in into the application you request is originating from or the very user performing the action does not have the required permission to perform such an operation.
Let's assume it is the first case (an unauthenticated user, who under normal circumstances has all rights to perform the intended action);
The obvious solution has to do with authenticating the user before performing the operation as you've guessed.
The question now is: how to authenticate a WordPress user via its in-built REST API?
The good news is: there is a range of options available for you to chose from based on your requirements and or preferences.
The snippet below demonstrates how you should go about it when using Backbone.js:
wp.api.loadPromise.done(function() {
// Create a new post
var post = new wp.api.models.Post({
title: 'Posted via REST API',
content: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
});
post.save(null, {
success: function(model, response, options) {
console.log(response);
},
error: function(model, response, options) {
console.log(response);
}
});
});
Remember to enqueue wp-api
in your functions.php
or plugin as below:
/**
* Either of the two can be used to enqueues in-built WP-API;
* not both as any of them enables you achieve the same result: to enqueue wp-api.
* The only difference between them is that one does it independently without any condition
* while the other does so with a condition: to enqueue it as a dependency for your script.
*/
function wp_api() {
// Use the line below to enqueue directly
// (should your code directly reside in your functions.php or plugin).
wp_enqueue_script( 'wp-api' );
// Use this option instead if you want to enqueue it (wp-api)
// as a dependency for your script (here, located in a js file) so as
// to ensure that your script gets loaded only after wp-api does as it depends on it.
wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api' ) );
}
add_action( 'init', 'wp_api' );
... more details on using Backbone JavaScript Client with WordPress REST API here.