How to use the WordPress REST API in Python - Robin Geuens (2023)

WordPress works around39.5% of all sites.

That's great, but if you've ever had a decent-sized blog, you know that keeping everything up to date is hard. Images break, links stop working, prices and product information become outdated, etc.

Going through all this content and manually updating it is a huge pain in the ass.

However, there are ways to speed it up. One of these ways is to use Python and the WordPress API. Every WP site has one, you just need to know how to use it.

In this article, I'll walk you through the basics (+ code) so you can get started with it.

How to use the WordPress REST API with Python

The essential

You need login information to use the API. If you can access your WordPress dashboard, you should already have them.

However, using a simple password to access the API is not very smart. You'll need to put your credentials in your code, so it wouldn't be very secure.

Instead, we'll create a password for the sole purpose of using Python. To do this, go to your WP Dashboard and click on "Users" -> "Profile".

If you scroll down you will see a section called "App Passwords"

How to use the WordPress REST API in Python - Robin Geuens (1)

Enter your app name and click "Add New App Password". This will generate a 24 character password that you can use in your python script.

The good thing about app passwords is that you can easily revoke them when you no longer need them. As an added security benefit, they cannot be used to access the WP dashboard.

While app passwords are more secure, I recommend generating a password just before running the script and invalidating the password when you're done.

Configure the API token

Now that we have our password, we can start working on our script. First we need to import the necessary packages and create the token.

solicitud de importación import base64wordpress_user = "su nombre de usuario" wordpress_password = "xxxx xxxx xxxx xxxx xxxx xxxx" wordpress_credentials = wordpress_user + ":" + wordpress_passwordwordpress_token = base64.b64encode(wordpress_credentials.encode()) wordpress_header = {'Autorización': 'Principal' + wordpress_token .decode('utf-8')}

Once the token is set up, we can start interacting with our WordPress site.

Using API to read WordPress posts

Let's start with the simplest: reading content. If you want, you can do it in your browser. Just navigate to the API URL (for example: However, if you want to do it in python, here is the code:

def read_wordpress_posts(): api_url = '' respuesta = request.get(api_url) respuesta_json = respuesta.json() print(response_json)

This is what we do:

api_url= This is the URL from which to get all our posts.
answer= make a GET request to the previously defined api_url.
json_response= we turn our response into something we can read.

This gives us a lot of JSON data to work with. It will look something like this:

{'id': 347, 'date': '2021-05-09T02:42:48', 'date_gmt': '2021-05-09T00:42:48', 'guid': {'rendering': 'https ://'}, 'modified': '2021-05-09T02:42:50', 'modified_gmt': '2021-05-09T00:42:50', 'slug': "think outside the box", "status": "post", "type": "post", "link": "", "title" : { 'rendered': "Why thinking outside the box is wasteful...

However, there is a problem. If you have a large site, the API returns a maximum of 100 posts per page. This is to ensure that the server does not time out when trying to process large requests.

If you want to receive all posts from your site, add parameters to the API URL to go to the next page. For example, if we want to get 100 posts per page and we want to get the second page, the API URL will look like this:

Now it's not practical to manually increase the pagination count, so you'll want to automate it. To do this, we first need to find out how many pages are available. This is quite easy as WordPress sends this the request header.

def get_total_pagecount(): api_url = '' response = request.get(api_url) pages_count = response.headers['X-WP - TotalPages ' ] return int ( pages_count )

By making a simple GET request and looking at the header, you can get the total number of pages available. We can then create a loop that iterates through all of them one by one, gets all the content, and adds it to the list. For example:

def read_wordpress_post_with_pagination(): total_pages = get_total_pagecount() current_page = 1 all_page_items_json = [] while current_page <= total_pages: api_url = f"{current_page}; &per_page=100" page_items = request.get(api_url) page_items_json = page_items.json() all_page_items_json.extend(page_items_json) current_page = current_page + 1 return all_page_items_json

Once you have the content, you can start manipulating it and doing cool things with it.

Using the API to create posts in WordPress

It's pretty boring to download a lot of content, so let's create a post instead. To do this, we need to load a few things.

def create_wordpress_post(): api_url = '' data = { 'title': 'Example wordpress post', 'status': 'publish', ' slug' ' : 'sample post', 'content': 'This is the content of the post' } response =,headers=wordpress_header, json=data) print(response)

api_url= again, this is the url where we need to send our data.
Danish= Contains all the arguments you want to send to WordPress. The list of things you can send is quite long, so I advise you to giveAPI Referenceread. In this example, we're just creating a simple post.
answer= we make a POST request and send the URL we should go to, our WordPress credentials, and the post details.

Once this is done, check your site and the post should be live (if you set the status to "publish").

How to use the WordPress REST API in Python - Robin Geuens (2)

This is of course a very basic example. In fact, it opens the door to having fun and creating content on WordPress in many different ways. For example, you can create a template for your content and use a CSV file to autofill multiple variables.

Using the API to update a post in WordPress

Updating a blog post is very similar to creating a new one. the only difference is that you need to add the post id to the api url.

If you're not sure where to find the post ID, you can either ping the API again or go to your WP dashboard and edit the post you want to update. You will see the post ID in the URL. For example:

You can then use the same code we used to create the post and update the content.

def update_wordpress_post(): api_url = '' post_id = '380' data = { 'title': 'Updated sample wordpress post', 'status ': 'publish', 'slug' : 'example-post-update', 'content': 'This is the content of the updated post' } response = + post_id,headers=wordpress_header, json=data ) print(response)

After running this code, check your site and the post should update.

How to use the WordPress REST API in Python - Robin Geuens (3)

However, there is a major problem with the content update. If you use the Gutenberg editor and use the API to download content, it does not send any data related to the blocks you use in the editor.

If you receive content, change it, and resubmit it, WordPress will lose control of the blocks you used in your post. It will return you to the classic editor, and if you try to automatically convert it to blocks, you risk turning everything into a custom HTML block.

This might be fine if you only have some text, but if you're using custom blocks like we doPiktochart, this method becomes useless. This is what I mean.

WordPress uses block data to tell the editor what type of block it is using. You can see this if you look at the versions:

How to use the WordPress REST API in Python - Robin Geuens (4)

Or you can export the XML of all your posts. The XML file also contains all the data for the block. For example:

However, simple does not mean easy. Finding a design that combines all 3 turned out to be more difficult than he thought.

Without this data, WP doesn't know which blocks to use and will fall back to the standard ones like paragraphs.

So I recommend exporting an XML file of all the posts or pages on your site and working with that. You have access to the block data, and if you use the API to send an update, WordPress will use that block data to figure out what type of block it is.

That way you can use the API and still be able to edit correctly in the editor if needed.

Using API to delete posts in WordPress

Deleting a post is easy. All you need is the API URL and the post ID and you're good to go.

def delete_wordpress_post(): api_url = '' post_id = '380' respuesta = request.delete(api_url + post_id, headers=wordpress_header) print(response)

Nothing else, to be honest.

Putting it all together

This post covers some basic ways to interact with the API. However, this is only the beginning. You can start combining them, add intermediate steps, or use a different API to streamline the process.

Here are some things you can do with the API:

  • Create a template for your content and use the CSV file to populate the variables
  • Create a report by getting all blog URLs and adding Google Analytics data to them
  • Download all content, check for outdated links and use a CSV file to change them to a different link
  • Download all content, check in Google search console and Google Analytics and remove all posts that have no more than 1 visitor per day
  • Download content, check for broken internal links, and use a machine learning algorithm to suggest a different URL. Then use the update function to update all broken internal links
  • Download content and automatically post title and URL to social media
  • Download content, search for headlines and automatically add jump links. Then add a table of contents right above the first part of H2

Once you try it yourself, you'll understand how powerful the API is. You will also start to save a lot of time by automating the subtasks.


How do I connect to WordPress REST API? ›

With WordPress, to fetch data from its API is as simple as composing a URL. For any WordPress site running at least version 4.7, add the following string to the end of your site's url: /wp-json/wp/v2 (e.g., ). Put that URL in your browser, and see what comes up.

How to connect to REST API in Python? ›

How to Use Python Requests with REST APIs
  1. Step 1: Install the Python Requests Module with pip Command on Your Terminal. Shell. ...
  2. Step 2: Next, you have to Request Data With GET. ...
  3. Step 3: Retrieve the Data You Want To (Here, the Random Pic of the Fox)
Dec 4, 2021

Can we use REST API in WordPress? ›

The WordPress REST API is an interface that allows external applications to access the data and functionality of the WordPress CMS. This tool lets developers integrate WordPress into third-party web applications and websites without needing to log into WordPress.

Can we integrate WordPress with Python? ›

WordPress has become the most used content management system (CMS) due in no small part to its application programming interface (API). The WordPress REST API enables WordPress to “talk” with other applications written in various languages — including Python.

How do I know if my REST API is working WordPress? ›

Is the WordPress REST API enabled? The best way to check is to visit this URL: If you see some information which seems related to your WordPress REST API, it works. If you see something, it means that, at least, your WordPress REST API is enabled.

How do I find my WordPress REST API base URL? ›

By default, if you have pretty permalinks enabled, the WordPress REST API “lives” at /wp-json/ . At our WordPress site`, we can access the REST API's index by making a GET request to`.

How to create REST API endpoint in Python? ›

To create an endpoint, we define a Python class (with any name you want) and connect it to our desired endpoint with api. add_resource , like this: Flask needs to know that this class is an endpoint for our API, and so we pass Resource in with the class definition.

Is Python good for REST API? ›

One of the most popular ways to build APIs is the REST architecture style. Python provides some great tools not only to get data from REST APIs but also to build your own Python REST APIs.

How to get response from rest API in Python? ›

The GET method is used to access data for a specific resource from a REST API; Python Requests includes a function to do exactly this. The response object contains all the data sent from the server in response to your GET request, including headers and the data payload.

How do I get data from my WordPress site? ›

The first option you can try is a query. This command allows you to retrieve data from your database in WordPress easily. You can retrieve all the content in your site's database using MySQL queries. The query will also include a loop that, by default, follows your parent theme code for your stored data will appear.

Is WordPress REST API fast? ›

Using the new WordPress REST API allows developers to create cutting-edge new features without using a ton of server-side resources. That means most features developed using the REST API will be faster than if developed using PHP.

What method does the WordPress REST API use for authentication? ›

Cookie authentication is the standard authentication method included with WordPress.

How do I make WordPress posts automatically in Python? ›

Here is an example of how to set up the connection:
  1. from wordpress_api import WordPressAPI wp = WordPressAPI( url='', username='yourusername', password='yourpassword' )
  2. post = wp. posts. ...
  3. import requests from bs4 import BeautifulSoup url = '' response = requests.
Jan 27, 2023

How to connect to WordPress database from Python? ›

Connecting to WordPress from Python using ODBC Driver for WordPress
  1. Step 1: Connect. import pyodbc cnxn = pyodbc.connect('DRIVER={Devart ODBC Driver for WordPress};User ID=myuserid;Password=mypassword;Security Token=mysecuritytoken')
  2. Step 2: Insert a row. ...
  3. Step 3: Execute query.

What is the best Python alternative to WordPress? ›

What is Django CMS? Django is one of the most popular open-source tools in web development. Django CMS is similar to WordPress, a Content Management System that is used by thousands of websites and organizations.

Why is WordPress REST API disabled? ›

If you received an error, it means the WordPress Rest API is disabled. You can enable it by activating your permalinks in WordPress. Visit Settings ➜ Permalinks within WordPress and without making any changes click Save changes. This causes WordPress to flush its rewrite rules, and can often resolve issues like this.

How to test WordPress REST API in Postman? ›

How to authenticate WP Rest APIs with Postman
  1. Step 1: Grab the current nonce.
  2. Step 2: Grab the wordpress_logged_in cookie.
  3. Step 3: Setup Postman to invoke the WP Rest API.
  4. Voila!! We did it. Now, we are able to authenticate the WordPress REST APIs from within Postman. Happy coding.
May 8, 2020

How do I call an external API in WordPress? ›

Go to the Connect To External API tab in the plugin to connect the External/third-party provider's API endpoints to WordPress. Select the PUT method from the Select Method dropdown. In the External API textbox, put the API endpoint that you want to connect it with WordPress.

What is the default URL for REST API? ›

The default URL to access the messaging REST API is: https://localhost:9443/ibmmq/rest/v1/messaging . If the host or port is changed from the default, or if HTTP is enabled, you can determine the URL by using the dspmqweb command.

What is the URL structure for REST API? ›

A REST API is accessed with an endpoint URL. The endpoint URL consists of a base URL, a resource path, and query parameters. The base URL is the internet host name for the REST API. The resource path is the address to the API resource.

How do I pull data from an API using Python requests? ›

  1. Register your App.
  2. Enable Microsft Graph Permissions.
  3. Authorization Step 1: Get an access code.
  4. Authorization Step 2: Use your access code to get a refresh token.
  5. Authorization Step 3: Use your refresh token to get an access token.
  6. Using Windows Task Scheduler.
Mar 18, 2020

How do I access API endpoint in Python? ›

  1. Step 1: Import the module. The most common library for making requests and working with APIs is the requests library. ...
  2. Step 2: Making an HTTP request. To make a request to the API, there are different types of requests like GET, POST etc. ...
  3. Step 3: To query the data by sending the params.
Dec 26, 2022

How to create API in Python step by step? ›

How to Create an API in Python with Flask – Step by Step
  1. Create the Student Class.
  2. Setup Your SQLite Database Connection.
  3. Make a Get Request.
  4. Get Record By ID.
  5. POST Request.
  6. Update Request.
  7. DELETE Request.
Jun 28, 2022

What is the difference between Python API and REST API? ›

3) API vs REST API: Protocol

The primary goal of API is to standardize data exchange between web services. Depending on the type of API, the choice of protocol changes. On the other hand, REST API is an architectural style for building web services that interact via an HTTP protocol.

What is the fastest API framework for Python? ›

To date, FastAPI is one of the fastest frameworks for building APIs with Python 3.6+. The framework took several characteristics from Flask, including its simplicity. The whole framework is built on Starlette and includes most of its features (templates, WebSockets, and GraphQL support).

What is the best framework to build REST API Python? ›

Django is the most popular Python framework, and it's heavily used for web development. Developers and designers love the batteries-included approach, in which Django REST framework provides all you need to build an application. This means a Django developer doesn't have to rely on separate libraries for functionality.

How to get JSON data from REST API in Python? ›

To get JSON from a REST API endpoint using Python, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept: application/json header tells the REST API server that the API client expects to receive data in JSON format.

How to get JSON data from POST request in Python? ›

Test Your JSON POST request using postman before executing
  1. Select POST request and enter your service POST operation URL.
  2. Click on Headers. In the key column enter Content-Type and in the Value column enter application/json .
  3. Click on the body section and click the raw radio button. enter your JSON data.
May 14, 2021

How does WordPress connect to database? ›

WordPress uses a database management system called MySQL, which is open source software. This means you'll sometimes hear your site's database referred to as a “MySQL database.” MySQL is what enables the database to store information and provide you with access to it.

How do I handle database in WordPress? ›

How To Create a WordPress Database
  1. Log in to your cPanel.
  2. Click the MySQL Database Wizard icon under the Databases section.
  3. Enter the database name in the Create Database Users area, and click Next Step.
  4. In Create Database Users, enter the database user name and password.
Sep 28, 2022

How do I get data from another database in WordPress? ›

To access data from another database in WordPress, you need to write a custom query using the $wpdb class. The $wpdb class allows you to interact with multiple databases in WordPress. You can then use the $posts and $postmeta variables to access the data from the other database.

What data format does WordPress REST API use? ›

The REST API uses JSON exclusively as the request and response format, including error responses.

What is WordPress REST limit? ›

Rate limits allow for configuring the number of requests a client can make within a certain interval. The default in WP Rest Cop is 500 requests per hour. The rate limit functionality requires a persistent object cache.

Which programming language is fast for REST API? ›

Python as a scripting language is fast and productive. You can create web-based applications quickly and the code is highly readable as the fundamental idea behind Python is to incorporate an easily readable code. Python syntax is easy to understand, well-defined and extensible.

Which authentication is best for REST API? ›

  • #1 API Key (identification only) One of the easiest ways to identify an API client is by using an API key. ...
  • #2 OAuth2 token. OAuth2 is a comprehensive industry standard that is widely used across API providers. ...
  • #3 External token or assertion. ...
  • #4 Token Exchange. ...
  • #5 Identity facade for 3 legged OAuth.
Feb 9, 2023

How do I pass authentication details in REST API? ›

The client must create a POST call and pass the user name, password, and authString in the Request headers using the /x-www-form-urlencoded content type. The AR System server then performs the normal authentication mechanisms to validate the credentials.

How do I enable REST API authentication in WordPress? ›

Log into your WordPress instance as an admin. Go to the WordPress Dashboard -> Plugins and click on Add New. Search for a WordPress REST API Authentication plugin and click on Install Now. Once installed click on Activate.

How do I fetch custom field data in WordPress? ›

To add a Custom Field, type in the Key (labeled “Name”) and Value, then click Add Custom Field. After it's added, you can delete or update it from buttons below the Key/Name: After you have used Custom Fields, the keys will form into a dropdown menu for easier selection.

How do I automate my WordPress site? ›

7 ways to automate your WordPress website
  1. Schedule posts for publishing. ...
  2. Install the latest plugin and theme updates. ...
  3. Create regular backups. ...
  4. Scan for security threats and malware. ...
  5. Assess your website's performance. ...
  6. Monitor your website for downtime. ...
  7. Clean your database.
Oct 27, 2020

How do I create a custom post in WordPress programmatically? ›

The code that programmatically create WordPress post
  1. $wordpress_post = array(
  2. 'post_title' => 'Post title',
  3. 'post_content' => 'Post Content',
  4. 'post_status' => 'publish',
  5. 'post_author' => 1,
  6. 'post_type' => 'page'
  7. wp_insert_post( $wordpress_post );
Jun 28, 2022

Can you connect WordPress to SQL? ›

You can use the SQL Gateway to configure a TDS (SQL Server) remoting service and set up a linked server for WordPress data. After you have started the service, you can use the UI in SQL Server Management Studio or call stored procedures to create the linked server.

Is Python compatible with WordPress? ›

WordPress has become the most used content management system (CMS) due in no small part to its application programming interface (API). The WordPress REST API enables WordPress to “talk” with other applications written in various languages — including Python.

Which is better Django or WordPress? ›

Django is no slouch when it comes to integrations, but since you often have to write a lot of additional code to get them to work, WordPress is the clear winner. It has a larger library of integrations to choose from, and they are easier to use.

Which platform is best for Python coding? ›

The most popular IDEs for experienced Python developers are PyCharm and Visual Studio Code. PyCharm is a full-featured IDE that offers many features, including code completion, code navigation, refactoring, and debugging.

How do I connect to REST API? ›

Step #1 – Enter the URL of the API in the textbox of the tool. Step #2 – Select the HTTP method used for this API (GET, POST, PATCH, etc). Step #3 – Enter any headers if they are required in the Headers textbox. Step #4 – Pass the request body of the API in a key-value pair.

How do I call WordPress REST API in Postman? ›

How to authenticate WP Rest APIs with Postman
  1. Step 1: Grab the current nonce.
  2. Step 2: Grab the wordpress_logged_in cookie.
  3. Step 3: Setup Postman to invoke the WP Rest API.
  4. Voila!! We did it. Now, we are able to authenticate the WordPress REST APIs from within Postman. Happy coding.
May 8, 2020

Where do I enter my WordPress API key? ›

Log into your WordPress instance as an admin. Go to the WordPress Dashboard -> Plugins and click on Add New. Search for a WordPress REST API Authentication plugin and click on Install Now. Once installed click on Activate.

How do you call an API in Python? ›

Make your API call
  1. def get_data(self, api):
  2. response = requests.get(f"{api}")
  3. if response.status_code == 200:
  4. print("sucessfully fetched the data")
  5. self.formatted_print(response.json())
  6. else:
  7. print(f"Hello person, there's a {response.status_code} error with your request")

How to call REST API with code? ›

Calling REST APIs
  1. Add a Datasource with OpenAPI specification. Datasource for REST service without OpenAPI specification.
  2. Add a service. Define the methods that map to the operations.
  3. Add a Controller. Inject the Service in the constructor. Add the REST endpoints.
  4. More examples.
  5. Further reading.

How to use REST API commands? ›

Running REST commands in process steps

Specify the complete URL of the command. For example, to use the command Get information about all applications on the server, specify the URL https:// :8443/cli/application , using the host name or IP address of your server for .

How to call API in Postman in Python? ›

Activity 1: Sending Requests to Our APIs Using Postman
  1. Create a request in Postman and get all the recipes.
  2. Use a POST request to create a recipe.
  3. Create a request to get all the recipes.
  4. Send an update request to modify the recipe that we have just created.
  5. Send a request to get a specific recipe.

How do I use Postman in WordPress? ›

How to Set up and Configure Postman SMTP on WordPress
  1. Step 1: Install Post SMTP Plugin.
  2. Step 2: Activate Post SMTP Plugin.
  3. Step 3: Troubleshooting Screen.
  4. Step 4: Start The Wizard.
  5. Step 5: Gmail SMTP Server.
  6. Step 6: Run Connectivity Test.
  7. Step 7: Connect to Mail Server.
  8. Step 8: Client ID and Client Secret.
Nov 16, 2022

How to automate REST API using Postman? ›

Creating API Collections
  1. Generate a token to call your api (in our case, we will get it manually from here).
  2. Send a POST request to create a user.
  3. Verify the response from the previous request.
  4. Send a GET request to get the created user details.
  5. Verify the data received is as expected.
  6. Delete the created user.
Oct 13, 2022

How to install API in WordPress? ›

Here's how to install the plugin:
  1. Download the WordPress REST API Basic Auth plugin.
  2. Log in to your WordPress Dashboard and go to Plugins -> Add New. Click on the Upload Plugin button and select the plugin's zip file.
  3. Go to the Installed Plugins menu and activate the plugin from there.
Feb 20, 2023

How do I integrate a third party API in WordPress? ›

Complete Procedure: How to Integrate 3rd-party API in WordPress?
  1. Step 1: Install and Activate the Plugin. ...
  2. Step 2: Setup the 3rd-party API. ...
  3. Step 3: Configure the Endpoint Settings. ...
  4. Step 4: Test the API Configuration. ...
  5. Step 5: Display Data Received Through API.
May 31, 2023

How do I add an API key to my API? ›

To create your application's API key:
  1. Go to the API Console.
  2. From the projects list, select a project or create a new one.
  3. If the APIs & services page isn't already open, open the left side menu and select APIs & services.
  4. On the left, choose Credentials.
  5. Click Create credentials and then select API key.

Where is the WordPress database stored? ›

Where Is My WordPress Database Stored? WordPress uses MySQL as its database management system, which is software installed on your WordPress hosting server. Your WordPress database is also stored on the same server. This location is not accessible on most shared hosting environments.


Top Articles
Latest Posts
Article information

Author: Golda Nolan II

Last Updated: 30/11/2023

Views: 5581

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.