How to upload an image to wordpress.com through REST API in python
-
I am trying to upload an image to my wordpress.com site (not WP installed on my own site) using WordPress’ REST API in python. There are a few examples of how to do this on SO when the WordPress site is hosted by the user. But I could not find any example when the site is on wordpress.com. I tried to follow the example of a similar problem here and used the code below. I tried
url = 'https://public-api.wordpress.com/wp/v2/sites/' + domain + '/media'as the access URL but got a 400 (malformed) response code.I generated wp_token as
wordpress_credentials = wordpress_user + ':' + wordpress_password wordpress_token = base64.b64encode(wordpress_credentials.encode()) wp_token = wordpress_token.decode('utf-8')wordpress_passwordhere is the app password.How do I debug why I am getting the 400 response? Appreciate any help.
import json, os, subprocess def wp_upload_image2(domain, wp_token, img_path): # Form the url url = 'https://public-api.wordpress.com/rest/v1.1/sites/' + domain + '/media/new' # Extract the filename and the extension from the img_path extension = img_path[img_path.rfind('.')+1 : len(img_path)] print("img_path: ", img_path, "Filename: ", img_path, "extension: ", extension) # Now form the header headers = { 'Authorization': 'BEARER ' + wp_token, } try: with open(img_path, 'rb') as fp: print("Successfully opened file!") files = { 'media[]': fp, } rs = requests.post(url, headers=headers, files=files) print("Response from WP: ", rs) return(rs) except IOError as e: print(f"Couldn't open file ({e})")The blog I need help with is: (visible only to logged in users)
- The topic ‘How to upload an image to wordpress.com through REST API in python’ is closed to new replies.