rest_cannot_create Sorry, you are not allowed to create posts as this user in WordPress REST API

The issue

When we were working with WordPress REST API, we got into the this issue. We were trying to create a post in WordPress using WordPress post API (/wp-json/wp/v2/posts). Following is the issue:

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

Reasons

This can happen in multiple reasons.

  • In our case this happend because the very first attempted we tried the post request without any authentication.
  • Then we tried the post request with a user credential who didn’t have access

Solution

We had to use a JWT plugin to generate a authentication token. Following is the plugin link:
https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

Once we got the token we call the post request like below and it solved the issue:

create_post_url = WP_API_ENDPOINT + "/wp/v2/posts"
headers = {'content-type': 'application/json', 'Authorization': "Bearer " + wordpress_token}

WordPress REST API endpoints
How to use WordPress REST API

Share