Upload Images to Your WordPress Site with Python Via the REST API
Up to now, I have been using Imgur for programmatically creating and uploading images, but I don't really like being beholden to the generosity of a 3rd party service, especially as the images will be used in my blog articles.
Enter the REST API for WordPress!
The REST API allows you to interact with the back end of your blog through the web, remotely or on the same server, it doesn't care so long as you can authenticate.
First, you will need to do the basics. If you are on the latest WordPress then you already have the API available. Otherwise follow the instructions.
If you are going to give 3rd parties access, or are concerned about security, use the oAuth API., otherwise basic is easy and quick.
Using the Rest API
Once you are all set up, you will interact using API endpoint URLs where you often need the IDs of the content you are working with, you can just grab them from the admin URLs while testing:
For my media library I use:
url = "https://MYURL.com/wp-json/wp/v2/media/"
You can post, delete or get that endpoint. I am posting up a new image so will use POST, and a list of files
files = {'file': open('tmp.png', 'rb')}
response = requests.request(
"POST",
url,
headers=headers,
files=files,
auth=('USER', 'PASS'))
You get back in the response a JSON object. You can get your new filename from there:
json = response.json()
guid = json.get('guid')
url = guid.get('raw')
print(url)
The whole API is very useful to explore, and is under development, so do check it out!
Thanks, for useful information.