How to upload images using wordpress REST api in python?
I've figured it out!
With this function I'm able to upload images via the WP REST api to my site (Photo Gear Hunter.) The function returns the ID of the image. You can then pass that id to a new post call and make it the featured image, or do whatever you wish with it.
def restImgUL(imgPath): url='http://xxxxxxxxxxxx.com/wp-json/wp/v2/media' data = open(imgPath, 'rb').read() fileName = os.path.basename(imgPath) res = requests.post(url='http://xxxxxxxxxxxxx.com/wp-json/wp/v2/media', data=data, headers={ 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fileName}, auth=('authname', 'authpass')) # pp = pprint.PrettyPrinter(indent=4) ## print it pretty. # pp.pprint(res.json()) #this is nice when you need it newDict=res.json() newID= newDict.get('id') link = newDict.get('guid').get("rendered") print newID, link return (newID, link)
To specify additional fields supported by the api such as alt text, description ect:
from requests_toolbelt.multipart.encoder import MultipartEncoderimport requestsimport osfileName = os.path.basename(imgPath)multipart_data = MultipartEncoder( fields={ # a file upload field 'file': (fileName, open(imgPath, 'rb'), 'image/jpg'), # plain text fields 'alt_text': 'alt test', 'caption': 'caption test', 'description': 'description test' })response = requests.post('http://example/wp-json/wp/v2/media', data=multipart_data, headers={'Content-Type': multipart_data.content_type}, auth=('user', 'pass'))
thanks to @my Year Of Code
.
my final working code:
import HOST = "https://www.crifan.com"API_MEDIA = HOST + "/wp-json/wp/v2/media"JWT_TOKEN = "eyJxxxxxxxxjLYB4" imgMime = gImageSuffixToMime[imgSuffix] # 'image/png' imgeFilename = "%s.%s" % (processedGuid, imgSuffix) # 'f6956c30ef0b475fa2b99c2f49622e35.png' authValue = "Bearer %s" % JWT_TOKEN curHeaders = { "Authorization": authValue, "Content-Type": imgMime, 'Content-Disposition': 'attachment; filename=%s' % imgeFilename, } # curHeaders={'Authorization': 'Bearer eyJ0xxxyyy.zzzB4', 'Content-Type': 'image/png', 'Content-Disposition': 'attachment; filename=f6956c30ef0b475fa2b99c2f49622e35.png'} uploadImgUrl = API_MEDIA resp = requests.post( uploadImgUrl, # proxies=cfgProxies, headers=curHeaders, data=imgBytes, )
return 201
means Created OK
response json look like:
{ "id": 70393, "date": "2020-03-07T18:43:47", "date_gmt": "2020-03-07T10:43:47", "guid": { "rendered": "https://www.crifan.com/files/pic/uploads/2020/03/f6956c30ef0b475fa2b99c2f49622e35.png", "raw": "https://www.crifan.com/files/pic/uploads/2020/03/f6956c30ef0b475fa2b99c2f49622e35.png" },...
more details refer my (Chinese) post: 【已解决】用Python通过WordPress的REST API上传图片