0

I have a Wordpress site hosted by Bluehost, generic web store using WooCommerce and Elementor. I can add and edit products via the WooCommerce API without trouble, but whenever I try to post to the Wordpress REST API I get the error:

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

My python code is:

import base64
import requests

def post_post(title, content):
    url = 'https://mysite.com/wp-json/wp/v2/posts'
    username = 'user'
    password = 'applicationpassword'
    credentials = username + ':' + password
    token = base64.b64encode(credentials.encode())
    authorization = 'Basic' + token.decode('utf-8')

    post_data = {
        'title': title,
        'content': content
        }
    header = {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
        'Authorization': authorization
        }
    response = requests.post(url, headers=header, json=post_data)
    return response

r = post_post("title", "content")
r.text

I have tried editing the .htaccess file as described in this topic but it did not work: authentication issue with rest api - rest_cannot_create

Any help would be greatly appreciated! I'm tearing my hair out here ;)

2 Answers 2

1

Sheepishly:

The authorization field needs a space between "Basic" and the token. Problem solved.

0

You say you can post WooCommerce products successfully, so I presume you know that WooCommerce and WordPress have different APIs and different credentials. The code you have above is for the WordPress API and so I want to make sure that you know you need to create a user application password (in WordPress users/edit users) to use the WordPress API. The normal credentials you use to log into the site will not work.

3
  • Yes, thanks for clarifying - I do realize they are different APIs and need different credentials. The application password I'm using was generated for the WordPress user in the WP settings (user has admin privileges). Commented Nov 8, 2024 at 11:55
  • I've tried the application password with and without the spaces, and I've run my token through a separate base64 decoder just to make sure that is working. Commented Nov 8, 2024 at 12:17
  • are you using a caching plugin? I've seen caching cause that error. Commented Nov 8, 2024 at 21:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.