- How to use WordPress REST API from python?
- Step 1: Define WordPress end point
- Step 2: Generate WordPress token
- Step 3: Use post call to create post in WP
- Saved searches
- Use saved searches to filter your results more quickly
- BRdhanani/wordpress-rest-api-with-python
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Saved searches
- Use saved searches to filter your results more quickly
- bdeshayes/WPrestAPIpython
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
How to use WordPress REST API from python?
WordPress REST API is very useful. used heavily by the WordPress developer community. The WordPress REST API integration to the WordPress core made WordPress more powerful.
In this post, we are going to discuss step by step guide about doing WordPress REST API calls from the python script.
Step 1: Define WordPress end point
wordpress_token = "" wordpress_credential = ", "password": ""> WP_API_ENDPOINT = "http://domain.cefalo.com/wp-json"
Step 2: Generate WordPress token
def generate_wordpress_token(): global wordpress_token token_url = WP_API_ENDPOINT + "/jwt-auth/v1/token" try: token_response = requests.post(url = token_url, data = wordpress_credential) if token_response and token_response.status_code == 200: token_data = token_response.json() if token_data: wordpress_token = token_data["token"] except (OSError, IOError) as e: logger.critical("Could not generate the token using this endpoint: %s.", token_url)
Step 3: Use post call to create post in WP
def import_post_to_wordpress(pp_json): global wordpress_token result = <> if pp_json['title']: if not wordpress_token: generate_wordpress_token() if wordpress_token: create_post_url = WP_API_ENDPOINT + "/wp/v2/product" headers = pp_json['slug'] = slugify(pp_json['title']) get_response = requests.get(create_post_url + "?slug=" + pp_json['slug']).json() if get_response: post_json = get_response[0] if post_json: update_post_url = create_post_url + "/" + str(post_json['id']); try: put_response = requests.put(url = update_post_url, json=pp_json, headers=headers) if put_response and put_response.status_code == 200: result = put_response.json() except (OSError, IOError) as e: logger.critical('Could not update the book: %s.', post_json['id']) else: try: post_response = requests.post(url = create_post_url, json=pp_json, headers=headers) if post_response and post_response.status_code == 201: result = post_response.json() except (OSError, IOError) as e: logger.critical('Could not create the book %s.', pp_json['title']) if result: logger.info('Imported post in WP %s.', result["id"]) return result["id"]
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
WordPress Rest API CRUD operation with python
BRdhanani/wordpress-rest-api-with-python
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Example of WordPress REST API with Python. we will fetch all posts, create one new post, update it and delete it using REST API with Python.
First of all, we need basic authentication for performing crud operation and it won’t work until you install a special plugin named application password to get the application password. Go to your dashboard -> plugin -> Add new and type application password in the search box.
Once you installed plugin go to your profile settings and scroll to the bottom. You will see one application password field will be added there. Type you application name and hit enter and popup will appear with a password. Copy generated password from popup.
It’s time to go through the python 👽
Now, Create one file with the .py extension. You can give it any name (for example app.py).
Import some required packages: import requests import json import base64
url = "https://example.com/wp-json/wp/v2/posts" user = "your-username" password = "your-application-password" credentials = user + ':' + password token = base64.b64encode(credentials.encode()) header = responce = requests.get(url , headers=header) print(responce)
Let’s understand this code. URL is the URL of the site from which you want to fetch posts. user is your admin username. password is the application password that you have generated just before. Encode your credentials and pass them in header authorization as shown in code. At the bottom of the line we are printing our response to see what we are getting. Now, open your terminal and run your app.py file. python app.py
To create a post we need to make the post request with some required parameters like URL, your JSON data. Let’s do that:
url = "https://example.com/wp-json/wp/v2/posts" user = "your-username" password = "your-application-password" credentials = user + ':' + password token = base64.b64encode(credentials.encode()) header = post = < 'title' : 'Hello World', 'status' : 'publish', 'content' : 'This is my first post created using rest API', 'categories': 5, // category ID 'date' : '2020-01-05T10:00:00' >responce = requests.post(url , headers=header, json=post) print(responce)
To update post you need to pass post id to tell REST API which post you want to update. Let’s see how to do that.
url = "https://example.com/wp-json/wp/v2/posts/" postID = 1 user = "your-username" password = "your-application-password" credentials = user + ':' + password token = base64.b64encode(credentials.encode()) header = post = < 'title' : 'Hello World Updated', 'content' : 'This is my first post created using rest API Updated' >responce = requests.post(url + postID , headers=header, json=post) print(responce)
Here, postID is the id of the post you want to update.
To delete a post we need to use delete requests provided by python.
url = "https://example.com/wp-json/wp/v2/posts/" user = "your-username" password = "your-application-password" credentials = user + ':' + password token = base64.b64encode(credentials.encode()) header = responce = requests.delete(url + postID , headers=header) print(responce)
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
accessing WordPress custom post type with meta fields via a python web app
bdeshayes/WPrestAPIpython
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
accessing WordPress custom post type with meta fields via a python web app
Install WordPress and add the REST-API.php file in the wp-contents/plugins directory.
If you are using WordPress 5 you will need the Classic Editor plugin to disable the new Gutemberg WYSIWYG fancy editor which does not show the new meta fields we just created.
You will also need to copy the JSON Basic Authentication plugin from https://github.com/WP-API/Basic-Auth into in the wp-contents/plugins directory.
Finally you will also copy archive-press_releases.php and single-press_releases.php into your active wp-contents/themes/twentynineteen directory (or whichever active theme you have)
When you go into your dashboard via /wp-admin login you will see two new menus.
One called Press Releases (above Appearance)
One called PR Generator (below Settings)
Go into the later one and click the button GENERATE SAMPLE DATA
After a little while (if you are online) this message will appear:
«All done — go to the menu Press Releases to see the result»
Our REST-API plugin just went over to https://www.prurgent.com/news/rss.php and copied a swad of press releases into our custom post type (aptly called press releases) which you can now see in the menu above Appearance.
If click Edit on one of those new posts and you scroll down to the bottom of the edit page you should see the 3 new meta fields (desk, link and topic).
I am running WAMP on Windows and my virtual host is aptly named REST-API, so by typing this url http://localhost/REST-API/press_releases/ I activate my archive-press_releases.php template which shows all those custom posts with the meta fields at the top.
if you type this url http://localhost/REST-API/wp-json/wp/v2/press_releases you will see a load of json encoded data which we will transact now from the python end.
Note: The press release posts are a different kettle of fish from the standard WordPress posts because they carry 3 extra meta fields (topic, desk and link). They won’t show up on your normal homepage but on a page of their own aptly called /press_releases
I have also installed python 3.7 on my windows laptop and I can run
INFO:root:Starting httpd on port 3000.
So by pointing my browser to http://localhost:3000/ I can see WordPress REST API Python App as well as the WordPress site running on WAMP in two separate tabs.
Let the fun begin. By clicking the Load from WP menu I repopulate my python side database with all the press releases grabbed from WordPress.
If you edit one of those not only the local python database (SQLite or MySQL) will be updated but also the corresponding custom post on WordPress will be synchronized!
This applies also if you delete one.
If you create a new press release on the Python app we first create it in WordPress with the REST API which returns the wpid (WordPress postID) so we can create a new record on the python side with our own id — ensuring the two sides remain in sync.
About
accessing WordPress custom post type with meta fields via a python web app