Cookie Consent by Free Privacy Policy Generator

Python & WordPress Rest API - Auto Publish a Post

Recently I started on a project that made sense for me to use the WordPress Rest API to speed up content publishing. In this post, i shall be demonstrating how quick and easy it is to connect to the WordPress Rest API using Python and programmatically post a new post.

Let's start with importing the Python libraries that we will be using for posting directly to the Wordpress API.

Code:
# import libs
import requests
import json
import base64

This next part is how we connect to the Rest API. Make sure you replace the login credentials with your own credential data.

When you have your login credentials set, go ahead and run the script. You should post a basic post to your default WordPress post category. If that worked as expected, go ahead and rework the JSON array to suit your requirements.

Code:
# connect to wordpress
url = "https://demodomain.com/wp-json/wp/v2/posts"
user = "myadmin"
password = "xxxx oooo xxxxx oooo xxxxx oooo"

credentials = user + ':' + password
token = base64.b64encode(credentials.encode())

header = {'Authorization': 'Basic ' + token.decode('utf-8')}

#post to wordpress
post = {
 'title'    : 'Hello World',
 'status'   : 'publish',
 'content'  : 'This is my first post created using rest API',
 'date'   : '2022-28-08T22:00:00'
}
responce = requests.post(url , headers=header, json=post)
print(responce)

Thanks for reading. I'm still in the process of learning the WordPress Rest API, so above, I recommend trying it out locally or on a clean installation of WordPress.
 
Back
Top