Last Updated on 2021-10-17 by Clay
Recently, some netizens asked me about how to publish articles on WordPress through program. I took this opportunity to introduce REST API that was achieve the purpose of publishing articles.
What is REST API?
REST (Representational State Transfer) API is a relatively simple structure of the construction style of network transmission information. Users only need to set the HTTP parameters and attributes according to their own needs, and then they can use different software and programs to make requests on the server interface.
So you can think of REST as a style.
What I want to record today is the so-called WordPress REST API, which is a programming interface designed by WordPress for developers.
If my explanation is not complete, please refer to the official document.
We still need to finish the following 2 steps:
- Create an Application Passwords
- Write the program to operation
But the steps are not complicated.
Application Passwords
In WordPress 5.6 and later version, this function has been enable by default; if you have a lower version, it is recommended to search for related plugin, such as Application Passwords to enable it.
First go to the backend and find Users > Profile in the left menu.
Find the Application Passwords field and set a new application name. Here you can name a meaningful name to help you identification.
After creating, you will see the password generated by random.
xxxx xxxx xxxx xxxx xxxx xxxx
Finally, don’t forget Update Profile (on the page bottom).
Write the program
In this section, I use python programming language to post request. If you have another familiar language, of course you can use it.
I will record the following operations:
- Confirm REST API can visit the website
- Publish an article
- Update an article
- Delete an article
Confirm REST API can visit the website
This is an important step. If the HTTP Status Code is not 200 after you post, you need to search for more information on Internet to troubleshoot your problem.
# coding: utf-8
import base64
import json
import requests
from pprint import pprint
def main():
# Init
url = "https://YOURS.com/wp-json/wp/v2/posts"
username = "USERNAME"
password = "PASSWORD"
credentials = "{}:{}".format(username, password)
token = base64.b64encode(credentials.encode())
# Header
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
"Authorization": "Basic {}".format(token.decode("utf-8")),
"content-type": "application/json",
}
# Check
r = requests.get(
url,
headers=headers,
)
# Print
print(r)
if __name__ == "__main__":
main()
Output:
<Response [200]>
Here are a few important parameters:
url
: Your WordPress website REST API addressusername
: Your webmaster account (or email)password
: It is not really password but the Application Passwords we generated.
If the program returns a status code of 200, congratulations! Your WordPress website will probably have no problem using the REST API.
Publish an article
Publishing an article is very similar to the operation just now, except that it has changed from get()
to post()
.
And you need to set additional information about the article. Please refer to the code below for details:
# coding: utf-8
import base64
import json
import requests
from pprint import pprint
def main():
# Init
url = "https://YOURS.com/wp-json/wp/v2/posts"
username = "USERNAME"
password = "PASSWORD"
credentials = "{}:{}".format(username, password)
token = base64.b64encode(credentials.encode())
# Header
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
"Authorization": "Basic {}".format(token.decode("utf-8")),
"content-type": "application/json",
}
# Post info
post = {
"title": "This is a REST API test",
"content": "Accessed.",
"status": "draft",
}
# Post
r = requests.post(
url,
headers=headers,
json=post,
)
# Print
pprint(r.text)
if __name__ == "__main__":
main()
Output:
('{"id":5204,"date":"2021-03-22T04:58:33","date_gmt":"2021-03-22T04:58:33","guid":{"rendered":"https:\\/\\/clay-atlas.com\\/?p=5204","raw":"https:\\/\\/clay-atlas.com\\/?p=5204"},"modified":"2021-03-22T04:58:33","modified_gmt":"2021-03-22T04:58:33","password":"","slug":"","status":"draft","type":"post","link":"https:\\/\\/clay-atlas.com\\/?p=5204","title":{"raw":"This '
'is a REST API test","rendered":"This is a REST API '
'test"},"content":{"raw":"Accessed.","rendered":"<p>Accessed.<\\/p>\\n","protected":false,"block_version":0},"excerpt":{"raw":"","rendered":"<p>Accessed.<\\/p> ...
If the information above is returned, it means that the publication is successful. You should be able to see the draft (If you want to publish, change status
to “publish”) we just added in the backend:
The content is the same as the one just set.
Update an article
Do you remember the article ID: 5204 printed on the screen after we execute the program? Of course, you can update the article content via article ID.
You can refer to the following code:
# coding: utf-8
import base64
import json
import requests
from pprint import pprint
def main():
# Init
url = "https://YOURS.com/wp-json/wp/v2/posts"
username = "USERNAME"
password = "PASSWORD"
credentials = "{}:{}".format(username, password)
token = base64.b64encode(credentials.encode())
# Header
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
"Authorization": "Basic {}".format(token.decode("utf-8")),
"content-type": "application/json",
}
# Post info
post_id = 5204 # <--- add post id
post = {
"title": "This is a REST API test",
"content": "Updated!", # <--- change the content
"status": "draft",
}
# Post
r = requests.post(
"{}/{}".format(url, post_id), # <--- change the url
headers=headers,
json=post,
)
# Print
pprint(r.text)
if __name__ == "__main__":
main()
Output:
After running the program, open the article again, you should find that the content of the article has been updated.
Delete an article
To delete an article, you only need the article ID and change post()
to delete()
.
# coding: utf-8
import base64
import json
import requests
from pprint import pprint
def main():
# Init
url = "https://YOURS.com/wp-json/wp/v2/posts"
username = "USERNAME"
password = "PASSWORD"
credentials = "{}:{}".format(username, password)
token = base64.b64encode(credentials.encode())
# Header
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
"Authorization": "Basic {}".format(token.decode("utf-8")),
"content-type": "application/json",
}
# Post info
post_id = 5204
# Delete
r = requests.delete( # <--- change "post" to "delete"
"{}/{}".format(url, post_id),
headers=headers,
)
# Print
pprint(r.text)
if __name__ == "__main__":
main()
Output:
At this time, we go to the backend and check again, we should find that this article has been moved into the trash.