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"

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:https://robingeuens.com/wp-json/wp/v2/posts). However, if you want to do it in python, here is the code:
def read_wordpress_posts(): api_url = 'https://robingeuens.com/wp-json/wp/v2/posts' 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 ://robingeuens.com/?p=347'}, 'modified': '2021-05-09T02:42:50', 'modified_gmt': '2021-05-09T00:42:50', 'slug': "think outside the box", "status": "post", "type": "post", "link": "https://robingeuens.com/blog/think-outside-the-box", "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:https://robingeuens.com/wp-json/wp/v2/posts?page=2&per_page=100
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 information.in the request header.
def get_total_pagecount(): api_url = 'https://robingeuens.com/wp-json/wp/v2/posts?page=1&per_page=100' 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"https://robingeuens.com/wp-json/wp/v2/posts?page={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 = 'https://robingeuens.com/wp-json/wp/v2/posts' data = { 'title': 'Example wordpress post', 'status': 'publish', ' slug' ' : 'sample post', 'content': 'This is the content of the post' } response = request.post(api_url,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").

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:https://robingeuens.com/wp-admin/post.php?post=380&action=edit
You can then use the same code we used to create the post and update the content.
def update_wordpress_post(): api_url = 'https://robingeuens.com/wp-json/wp/v2/posts/' 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 = request.post(api_url + post_id,headers=wordpress_header, json=data ) print(response)
After running this code, check your site and the post should update.

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:

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 = 'https://robingeuens.com/wp-json/wp/v2/posts/' 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.
FAQs
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., http://example.com/wp-json/wp/v2 ). Put that URL in your browser, and see what comes up.
How to connect to REST API in Python? ›- Step 1: Install the Python Requests Module with pip Command on Your Terminal. Shell. ...
- Step 2: Next, you have to Request Data With GET. ...
- Step 3: Retrieve the Data You Want To (Here, the Random Pic of the Fox)
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: https://yoursite.com/wp-json. 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 https://ourawesomesite.com`, we can access the REST API's index by making a GET request to https://ourawesomesite.com/wp-json/`.
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? ›- from wordpress_api import WordPressAPI wp = WordPressAPI( url='https://yourwebsite.com', username='yourusername', password='yourpassword' )
- post = wp. posts. ...
- import requests from bs4 import BeautifulSoup url = 'https://www.bbc.com/news' response = requests.
- Step 1: Connect. import pyodbc cnxn = pyodbc.connect('DRIVER={Devart ODBC Driver for WordPress};User ID=myuserid;Password=mypassword;Security Token=mysecuritytoken')
- Step 2: Insert a row. ...
- Step 3: Execute query.
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? ›- Step 1: Grab the current nonce.
- Step 2: Grab the wordpress_logged_in cookie.
- Step 3: Setup Postman to invoke the WP Rest API.
- Voila!! We did it. Now, we are able to authenticate the WordPress REST APIs from within Postman. Happy coding.
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? ›
- Register your App.
- Enable Microsft Graph Permissions.
- Authorization Step 1: Get an access code.
- Authorization Step 2: Use your access code to get a refresh token.
- Authorization Step 3: Use your refresh token to get an access token.
- Using Windows Task Scheduler.
- Step 1: Import the module. The most common library for making requests and working with APIs is the requests library. ...
- Step 2: Making an HTTP request. To make a request to the API, there are different types of requests like GET, POST etc. ...
- Step 3: To query the data by sending the params.
- Create the Student Class.
- Setup Your SQLite Database Connection.
- Make a Get Request.
- Get Record By ID.
- POST Request.
- Update Request.
- DELETE Request.
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.
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? ›- Select POST request and enter your service POST operation URL.
- Click on Headers. In the key column enter Content-Type and in the Value column enter application/json .
- Click on the body section and click the raw radio button. enter your JSON data.
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? ›- Log in to your cPanel.
- Click the MySQL Database Wizard icon under the Databases section.
- Enter the database name in the Create Database Users area, and click Next Step.
- In Create Database Users, enter the database user name and password.
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.
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? ›- Schedule posts for publishing. ...
- Install the latest plugin and theme updates. ...
- Create regular backups. ...
- Scan for security threats and malware. ...
- Assess your website's performance. ...
- Monitor your website for downtime. ...
- Clean your database.
- $wordpress_post = array(
- 'post_title' => 'Post title',
- 'post_content' => 'Post Content',
- 'post_status' => 'publish',
- 'post_author' => 1,
- 'post_type' => 'page'
- wp_insert_post( $wordpress_post );
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? ›- Step 1: Grab the current nonce.
- Step 2: Grab the wordpress_logged_in cookie.
- Step 3: Setup Postman to invoke the WP Rest API.
- Voila!! We did it. Now, we are able to authenticate the WordPress REST APIs from within Postman. Happy coding.
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? ›- def get_data(self, api):
- response = requests.get(f"{api}")
- if response.status_code == 200:
- print("sucessfully fetched the data")
- self.formatted_print(response.json())
- else:
- print(f"Hello person, there's a {response.status_code} error with your request")
- Add a Datasource with OpenAPI specification. Datasource for REST service without OpenAPI specification.
- Add a service. Define the methods that map to the operations.
- Add a Controller. Inject the Service in the constructor. Add the REST endpoints.
- More examples.
- Further reading.
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:// ucd-server.example.com :8443/cli/application , using the host name or IP address of your server for ucd-server.example.com .
How to call API in Postman in Python? ›
- Create a request in Postman and get all the recipes.
- Use a POST request to create a recipe.
- Create a request to get all the recipes.
- Send an update request to modify the recipe that we have just created.
- Send a request to get a specific recipe.
- Step 1: Install Post SMTP Plugin.
- Step 2: Activate Post SMTP Plugin.
- Step 3: Troubleshooting Screen.
- Step 4: Start The Wizard.
- Step 5: Gmail SMTP Server.
- Step 6: Run Connectivity Test.
- Step 7: Connect to Mail Server.
- Step 8: Client ID and Client Secret.
- Generate a token to call your api (in our case, we will get it manually from here).
- Send a POST request to create a user.
- Verify the response from the previous request.
- Send a GET request to get the created user details.
- Verify the data received is as expected.
- Delete the created user.
- Download the WordPress REST API Basic Auth plugin.
- 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.
- Go to the Installed Plugins menu and activate the plugin from there.
- Step 1: Install and Activate the Plugin. ...
- Step 2: Setup the 3rd-party API. ...
- Step 3: Configure the Endpoint Settings. ...
- Step 4: Test the API Configuration. ...
- Step 5: Display Data Received Through API.
- Go to the API Console.
- From the projects list, select a project or create a new one.
- If the APIs & services page isn't already open, open the left side menu and select APIs & services.
- On the left, choose Credentials.
- Click Create credentials and then select API key.
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.