Upload Images to Your WordPress Site with Python Via the REST API

in #programming6 years ago

verification-token.png

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.

registered-apps.png

json.png

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:

url.png

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)

Screenshot from 2018-03-19 17-03-48.png

The whole API is very useful to explore, and is under development, so do check it out!

Sort:  

Thanks, for useful information.

Coin Marketplace

STEEM 0.20
TRX 0.14
JST 0.030
BTC 64785.95
ETH 3471.44
USDT 1.00
SBD 2.51