how to authenticate for the REST API from a plugin and from command line

GET requests, like listing posts, doesn’t need authentication at least you need to get private posts. Your problem is that you are using a route/endpoint that doesn’t exist.

In WordPress 4.4, WP REST API infrastructure was merged, endpoints didn’t; they will be merged in WordPress 4.5 (as WordPress 4.6 it seems endpoints are still don’t included in core). You need to define your own endpoints or install the plugin to use the default endpoints it provides.

For example (not tested, just written here):

add_action( 'rest_api_init', 'cyb_register_api_endpoints' );
function cyb_register_api_endpoints() {

    $namespace="myplugin/v1";

    register_rest_route( $namespace, '/posts/', array(
        'methods' => 'GET',
        'callback' => 'cyb_get_posts',
    ) );

}

function cyb_get_posts() {

    $args = array(
         // WP_Query arguments
    );

    $posts = new WP_Query( $args );

    $response = new WP_REST_Response( $posts );

    return $response;

}

Then, you can get the posts:

https://example.com/myplugin/v1/posts/

Leave a Comment