Polish the Python Chips by Connecting Your App with WordPress

Here are some WordPress REST API uses for your applications and ways you can make use of Python to help these:
- Use predefined templates to enable your app to turn raw data into posts formatted that include explanations in a short time.
- Develop a back-office solution using Django and Python which displays offers that are limited in time for your clients each whenever an object-specific sale or sales event takes place.
- Integrate Python scripts to run inside your WordPress website.
This guide will assist you to develop a straightforward Python console application that interacts to and runs operations through the WordPress REST API. The complete project code can be downloaded.
Installing and Configuring WordPress
Let's first install and run an WordPress site locally on the development machine. It's a great way to start using WordPress as you don't need to sign up for an account or purchase a domain to host your website.
When installing WordPress locally, some components are required to run on your computer, including the Apache web server local databases and the PHP language in which WordPress is written.
Dev is compatible with Windows, Mac, and Linux, and installs WordPress along with all its dependencies on your local computer.
Before you install Dev, you need to be running Docker running locally, so install then run Docker Engine. Docker Engine If you haven't yet.

If you launch the Dev Installer, Docker starts initializing immediately:

After that, you can select New WordPress site on the Create new Site menu:

This time, the Dev installer asks you to create the login credentials to the WordPress admin account:

After installation, Dev is a standalone application. Now you can access both the WordPress site (via the button to open the Site button) and also the WordPress admin page ( WP Admin button).


Now go to the Dev app and click the open site button. A new browser tab will open and show the home page of your WordPress site:

It's your WordPress blog where you can start writing. However, in order to allow Python access to and use the WordPress REST API, you must first configure WordPress' Admin. WordPress Admin.
Now click the WP Administrator button in the Dev app, then provide your user and password to gain access to your WordPress dashboard:

Once you're logged in, you'll see WordPress Dashboard:

WordPress utilizes cookie authentication as its primary method. But if you want to control it using the REST API then you need to authenticate yourself using a method that grants access to the WordPress REST API.
To do this, you'll need passwords for applications. These are 24-character long strings that WordPress generates and connects to an account of a user that is granted the right to run your site.
To use Application Passwords, click the plugin menu from the Dashboard and then type in the plugin with the same name. Install and then activate the Application Passwords Plugin:

To begin creating your application password, start by expanding to the users menu, then clicking All Users:

Then, you can click Edit below your admin user name:

Go to the Edit User page, and then look for your Application Passwords section. There, enter a title for the Application Password, which you'll be able to use in the future to authenticate your Python app requests and consume the REST API:

Click to add a new application password so WordPress can generate the random password of 24 characters for you:

Next, copy this password and save it in a safe location to use later. Keep in mind that you won't be able to access the password after closing this page.
Finally, you must configure your permalinks. WordPress permits you to design an unique URL structure to use to your archives and permalinks. Let's change it so that a WordPress post titled, e.g., "Your First WordPress Website" can be accessed through the intuitive URL https://your-website.local:port/your-first-wordpress-website/. This approach brings several benefits in terms of improved user-friendliness and appearance.
To set up permalinks, go to into the Options section and click to open the Permalinksmenu. Here, change the Common Settings to Post name:

Setting the structure of the permalink by using the Post name structure is also important since it will permit us to find posts later within our Python code by using the JSON format. If not, a JSON decoding error will be caused.
How to Control WordPress By Python
WordPress is developed in PHP however it also has a REST API that enables various programming languages, websites and applications to use the content. By exposing the WordPress information in a REST-based architecture means that it is available as JSON format. Thus, different services are able to be integrated with WordPress and perform create, read, update and delete (CRUD) operations , without the requirement of an installation on a locally-installed WordPress installation.
The next step is to build an easy Python application that will show you how you can use the WordPress REST API. It allows you to create, retrieve, update, and even delete post.
Make a brand new directory to host your new Python project and name it something like "PythonWordPress"
:
../PythonWordPress
You'll now create an environment virtual to your program, allowing it to manage an entirely separate set of installed Python applications, separating these from the system directories and avoiding version conflicts. Make a virtual space by executing the command venv:
command:
Python3 -m venv .venv
Now, run a command to activate the .venv virtual environment. The command is different for each OS:
- Windows:
.venvScriptsactivate
- Mac/Linux:
.venv/bin/activate
Next, store the settings associated with your WordPress account. To distinguish the configuration of your WordPress account from your Python code, create a .env file in your project directory. Then, include these variables in the file:
WEBSITE_URL=""
API_USERNAME=""
API_PASSWORD=""
The good news is that reading the data above with an Python application is simple. It is possible to install Python-dotenv, a Python-dotenv package to ensure that your app can access the configuration file .env file:
Want to know what we did to increase our traffic over 1000 per cent?
Join 20,000+ others who receive our newsletter every week with insider WordPress advice!
pip install Python-dotenv
Then, install the aiohttp which is an asynchronous HTTP client and server for Python:
pip install AIOhttp
Create a new file called app.py with the following codes:
Import asynciomenu_options = 1. 'List Posts' 2.define print_menu() for key:for the key menu_options.keys() for key in menu_options.keys():
print (key, '--', menu_options[key[key] )
async def main():while(True) print_menu() option = input_numberprinting_menu()
options equals input_number('Enter your choice ')
#Check which option was selected and follow up accordinglyif option == 1 1.print('Listing posts') ...')
elif option is 2:print('Retrieving the post ...')
else printprint('Invalid choice. Please enter a number between 1 and five.') def input_number(prompt):
while True:
try:
value = int(input(prompt))
except ValueError:
print('Wrong input. Enter a number. ...')
continue
in case value is zero:print("Sorry, your response must not be negative.") else:breakreturn valuein def input_text(prompt) in the following manner:when True:text equals input(prompt)
when len(text) == 0.print("Text is mandatory.") continue
else:
break
return text
if __name__=='__main__':
asyncio.run(main())
The code above will display a console menu, and requires you to input a number to choose an option. In the next phase, you'll extend this idea and add the code that enables you to list all posts and retrieve a specific post using its post id.
Fetching Posts in Code
To interact with WordPress REST API, you need to create an entirely new Python file. Create a file named wordpress_api_helper.py with the following content:
import aiohttp
import base64
import os
import json
from dotenv import load_dotenv
load_dotenv()
user=os.getenv("API_USERNAME")
password=os.getenv("API_PASSWORD")
async def get_all_posts():
async with aiohttp.ClientSession(os.getenv("WEBSITE_URL")) as session:
async with session.get("/wp-json/wp/v2/posts") as response:
print("Status:", response.status)
text = await response.text()
wp_posts = json.loads(text)
sorted_wp_posts = sorted(wp_posts, key=lambda p: p['id'])
print("=====================================")
for wp_post in sorted_wp_posts:
print("id:", wp_post['id'])
print("title:", wp_post['title']['rendered'])
print("=====================================")
async def get_post(id):
async with aiohttp.ClientSession(os.getenv("WEBSITE_URL")) as session:
async with session.get(f"/wp-json/wp/v2/posts/id") as response:
print("Status:", response.status)
text = await response.text()
wp_post = json.loads(text)
print("=====================================")
print("Post")
print(" id:", wp_post['id'])
print(" title:", wp_post['title']['rendered'])
print(" content:", wp_post['content']['rendered'])
print("=====================================")
This ClientSession
method above is executed asynchronously, and produces an session
object that is used by our application to carry out an HTTP GET operation against the /wp-json/wp/v2/posts
endpoint. The only difference between a request to retrieve all posts and a request for a specific one is that this last request passes a post id
parameter in the URL route: /wp-json/wp/v2/posts/id
.
Then, open app.py and open app.py file and insert an import
statement:
from wordpress_api_helper import get_all_posts and get_post
Next, modify the principal
function to call for the get_all_posts
and get_post
functions:
If option1.print('Listing post') ...')
are waiting to be read the post's get_all_posts()
Elif choice == 2:print('Retrieving the latest post ...')
id = input_number('Enter the post id as follows:)
await get_post(id)
Run the application:
python app.py
Then, you'll see the app menu.

Try option 1 to view the posts list that your Python app will retrieve, and alternative 2 to choose the post you want to view:

Coding Posts to Create Posts
To create a WordPress post in Python, begin by opening the wordpress_api_helper.py file and add the create_post
function:
async def create_post(title, content):
async with aiohttp.ClientSession(os.getenv("WEBSITE_URL")) as session:
async with session.post(
f"/wp-json/wp/v2/posts?content=content&title=title&status=publish"
, auth=aiohttp.BasicAuth(user, password)) as response:
print("Status:", response.status)
text = await response.text()
wp_post = json.loads(text)
post_id = wp_post['id']
print(f'New post created with id: post_id')
This code calls the post
function inside the session
object. It passes in the authentication
parameter beside the endpoint URL of the REST API. This auth
object is now populated with the WordPress user and the password you created using Application Passwords. Open the app.py file and insert the following code: create_post
and the menu:
using wordpress_api_helper import all posts create_post
menu_options = 1: 'List Posts' 2: 'Retri
Then add a third menu item:
elif option == 3:print('Creating the post ...')
title = input_text('Enter the title of your post and then enter the post title ')
content = input_text('Enter the contents of the post: ')
in the midst of waiting for create_post(title,"title,"Content")
elif option == 3:print('Await create_
After that, open the application then try the option 3 by entering a title and a content to create a new post in WordPress:

If you select option 1, it returns the ID and it will also return the name of the recently posted post

Also, you can visit your WordPress website to view the new post:

Updating Posts in Code
Open the wordpress_api_helper.py file and add the update_post
function:
async def update_post(id, title, content):
async with aiohttp.ClientSession(os.getenv("WEBSITE_URL")) as session:
async with session.post(
f"/wp-json/wp/v2/posts/id?content=content&title=title&status=publish"
, auth=aiohttp.BasicAuth(user, password)) as response:
print("Status:", response.status)
text = await response.text()
wp_post = json.loads(text)
post_id = wp_post['id']
print(f'New post created with id: post_id')
Then open the app.py file and insert the following code: update_post
as well as the menu
via wordpress_api_helper import Get_All_Posts create_post, get_post update_post
menu_options = 1. 'List Posts'. 2.
Then, add the fourth option in the menu:
elif option =equals 4:print('Updating an article'). ...')
id is input_number('Enter the post id in the format:)
title is input_text('Enter the title of your post: ')
thecontent input_text = input_text('Enter the post content text:)
are waiting for update_post(id and title)"content")
_
Run the application and try option 4, passing a post id, title, and contents to make changes to an existing post.

Choosing option 2 and passing the post's ID that has been updated will display the post's details the post that was added recently:

The deletion of posts in code
You may send the post ID to the REST API to remove a post.
Open the wordpress_api_helper.py file and add the delete_post
function:
async def delete_post(id):
async with aiohttp.ClientSession(os.getenv("WEBSITE_URL")) as session:
async with session.delete(
f"/wp-json/wp/v2/posts/id"
, auth=aiohttp.BasicAuth(user, password)) as response:
print("Status:", response.status)
text = await response.text()
wp_post = json.loads(text)
post_id = wp_post['id']
print(f'Post with id post_id deleted successfully. ')
Open your app.py file and include the code for import delete_post
and the menu:
via wordpress_api_helper import Get_All_Posts make_posts, get_posts, update_post, delete_post
menu_options (1: List Posts'; 2: Update Posts');
Then, add a fifth choice menu:
Elif option5.print('Deleting the post') ...')
id = input_number('Enter the post's ID: ')
wait for delete_post(id)
Then, run the application and test the option 5 passing an id to delete the current post from WordPress:

Notice: The post that was deleted may still appear if you choose to run the list of posts option:

To confirm that you've deleted the post, hold it for some time and then try the list of posts option again. That's all there is to it!
Summary
With the help of WordPress REST API, as well as Python's HTTP client library, Python apps and WordPress are able to collaborate and communicate to each other. The advantage of using the REST API is that it lets you to operate WordPress remote from the Python app, where Python's powerful language enables automated content creation that follows the desired format and frequency.
Dev makes creating and developing a local WordPress site quick and easy. It is a locally-hosted environment to create WordPress themes as well as plugins. Additionally, it offers a simplified deployment model courtesy of its Docker-based, self-contained installation model.
What's your experience working using Python or WordPress?
Save time, costs and increase site performance:
- Instant help 24/7 support from WordPress hosting specialists, 24 hours a day.
- Cloudflare Enterprise integration.
- Global audience reach with 35 data centers worldwide.
- Optimization with the built-in Application Performance Monitoring.