How to create a post with WP REST API v2

Posted by

I’m trying to post an article to WordPress use WP REST API. before I do this, I check lost’s information.

Official doc:
https://developer.wordpress.org/rest-api/reference/posts/#arguments

Basic auth(WordPress plugin):
https://github.com/WP-API/Basic-Auth

First install Basic-Auth plugin.

Now we start it:

I’m using Postman as a client and can see it that correctly set “Authorization” header in the request.

Post url:http://host.com/wp-json/wp/v2/posts
Body(application/json):
{
    "title": "Your Post Title",
    "content": "Your post content",
    "status": "publish"
}

But I get the response like this:

{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}

I have lots of Google, here I give a solution to fix it, and a way how to debug it yourself.

Apache Rewrite

You may need to know the basic use of apache rewrite if you use apache.

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

Debug

Add RewriteRule in .htaccess or httpd-app.conf(bitnami)

   RewriteEngine On
   RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

This rule is mean REDIRECT_REMOTE_USER =Authorizaiton.

https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_e

Add a log to basic-auth.php in Basic-Auth code:

function json_basic_auth_handler( $user ) {
	global $wp_json_basic_auth_error;

	$wp_json_basic_auth_error = null;

	var_dump($_SERVER);
	// Don't authenticate twice
.........
}

zip and upload to WordPress.

Post again with postman, you got response like this:

  ["REMOTE_USER"]=>
  string(30) "Basic dddddddd="
  ["SCRIPT_URL"]=>
  string(20) "/wp-json/wp/v2/posts"
  ["REDIRECT_STATUS"]=>
  string(3) "200"
  ["REDIRECT_REMOTE_USER"]=>
  string(30) "Basic ddddddddd="
  ["REDIRECT_SCRIPT_URI"]=>

You will see some value like REMOTE_USER, REDIRECT_REMOTE_USER, next we fix the plugin:

	if ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) {
		$authorization = \sanitize_text_field( \wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] ) );
	}
	else if ( isset( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ) {
		$authorization = \sanitize_text_field( \wp_unslash( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) );
	}
	else if ( isset( $_SERVER['REDIRECT_REMOTE_USER'] ) ) {
		$authorization = \sanitize_text_field( \wp_unslash( $_SERVER['REDIRECT_REMOTE_USER'] ) );
	}

On “else if” case in the code to fixed rest_cannot_create bug. Test it with postman, the response is ok now.

Test uese “wpapi”

https://github.com/WP-API/node-wpapi

var WPAPI = require('wpapi');

console.log('log');

function create() {
    return new Promise(function(resolve, reject) {
        var wp = new WPAPI({
            endpoint: 'http://domain.com/wp-json',
            // This assumes you are using basic auth, as described further below
            username: 'user',
            password: 'pass'
        });
        wp.posts().create({
            // "title" and "content" are the only required properties
            title: 'Your Post Title',
            content: 'Your post content',
            // Post will be created as a draft by default if a specific "status"
            // is not specified
            status: 'publish'
        }).then(function(response) {
            // "response" will hold all properties of your newly-created post,
            // including the unique `id` the post was assigned on creation
            console.log(response.id);
            resolve(response);
        }).catch(function(error) {
            console.log(error);
        })
    })
}

create();