Search code examples
pythonwordpresswordpress-rest-api

Getting 200 Instead of 201 Status Code When Posting to WordPress with Python (Rest API)


I'm trying to create posts on my WordPress website via Python using the below code, but the response.json() just returns a 200 and a list of all the existing posts on my site in JSON format, i.e.:

[{'id': 1, 'date': '2023-07-15T17:46:24', 'date_gmt': '2023-07-15T17:46:24', 'guid': {'rendered': 'http://1234.5.6.7/?p=1'}, 'modified': '2023-07-24T03:58:06', 'modified_gmt': '2023-07-24T03:58:06', 'slug': 'slug', 'status': 'publish', 'type': 'post', 'link': 'https://www.example.com/2023/07/15/slug/', 'title': {'rendered': 'Title'}, 'content': {'rendered': '\t\t\n\t\t\t\t\t\t\t\t\te', 'protected': False}, 'excerpt': {'rendered': 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!\n', 'protected': False}, 'author': 1, 'featured_media': 3957, 'comment_status': 'open', 'ping_status': 'open', 'sticky': False, 'template': '', 'format': 'video', 'meta': {'footnotes': '', 'csco_singular_sidebar': '', 'csco_page_header_type': '', .........

This my python code:

import requests


# Set the URL of the WordPress REST API.
url = 'https://example.com/wp-json/wp/v2/posts'

# Set the username and password for your WordPress account.
username = 'UserNameHere'
password = 'MyPasswordHere'

# Create a JSON object that contains the post data.
post_data = {
    'title': 'My First Post',
    'content': 'This is my first python post!',
    'status': 'publish'
}


# Add the authorization header to the request.
headers = {'Authorization': 'Basic {}'.format(username + ':' + password)}

# Add the Content-Type header to the request.
headers['Content-Type'] = 'application/json'

# Use the requests library to make a POST request to the WordPress REST API.
response = requests.post(url, headers=headers, json=post_data)

# If the request is successful, the response will be a JSON object that contains the post data.
if response.status_code == 201:
    post = response.json()
    print(post)
else:
    print('Error:', response.status_code, response.json())

Any ideas?


Solution

  • Solution: Here is what ended up fixing it for me.

    1. change the url so it includes "wwww" -> 'https://www.example.com/wp-json/wp/v2/posts'

    2. The Basic Auth header value should be base64 encoded:

    import base64
    credentials = base64.b64encode(f"{username}:{password}".encode('utf-8')).decode('utf-8')
    headers = {
        'Authorization': f'Basic {credentials}',
        'Content-Type': 'application/json'
    }