WordPress REST API — Python

Type your WordPress address and after www.yourdomainname.com add wp-json/wp/v2/ and you will get build in REST API in json response.

That fancy future is great for posting articles via python or gathering data from the WP.

Before getting deeper how to post via REST API and Python make sure that your .htaccess file allows you to write. My .htaccess for WordPress part looks like these below. (Please make backup 1st before you change anything and be sure that you know what you are doing.)

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule># END WordPress

Now we are ready to generate Application Passwords Name under Users/profile/Application Passwords. Input your wanted WordPress App on My Phone Name and click on Add New Application Password.

After you made new Application Password Name popup window will appear with a unique code. Please store it in a safe place. (In case that you didn’t save it. Delete old username and create new one.)

Now everything, that allows your python script to communicate with WP is set so is time to post to it with the code below.

import requests
import base64
import json

with open('...config.json') as json_file:
    pythonapp = json.load(json_file)

url = "https://tokensquant.com/wp-json/wp/v2/posts"

user = "user"
data_string = user + ':' + pythonapp["secret"]

token = base64.b64encode(data_string.encode())

headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
title = "Name of my article"
content = 'Test content'

post = {'date': '2021-09-01T08:00:35',
        'title': title,
        'slug': 'rest-api-' + title,
        'status': 'publish',
        'content': content,
        'author': '1',
        'categories': [11],
        'excerpt': title,
        'format': 'standard'

r = requests.post(url, headers=headers, json=post)

For posting in right category, please make sure you set wanted category ID. At your WP go to categories and hoover up category with mouse and in left lower corner where full address is shown your category ID will appear.

Changing dates, titles etc is up to you and sky is the limit now.

Updating articles, collecting them and making other cool stuff is possible as well. Please check official WordPress tutorial for these.