plean plean - 4 months ago 121
Python Question

Python Request: Post Images on Facebook using Multipart/form-data

I'm using the facebook API to post images on a page, I can post image from web using this :

import requests

data = 'url=' + url + '&caption=' + caption + '&access_token=' + token
status = requests.post('https://graph.facebook.com/v2.7/PAGE_ID/photos',
data=data)
print status


But when I want to post a local image (using multipart/form-data) i get the error :
ValueError: Data must not be a string.


I was using this code:

data = 'caption=' + caption + '&access_token=' + token
files = {
'file': open(IMG_PATH, 'rb')
}

status = requests.post('https://graph.facebook.com/v2.7/PAGE_ID/photos',
data=data, files=files)
print status


I read (Python Requests: Post JSON and file in single request) that maybe it's not possible to send both data and files in a multipart encoded file so I updated my code :

data = 'caption=' + caption + '&access_token=' + token
files = {
'data': data,
'file': open(IMG_PATH, 'rb')
}

status = requests.post('https://graph.facebook.com/v2.7/PAGE_ID/photos',
files=files)
print status


But that doesn't seem to work, I get the same error as above.

Do you guys know why it's not working, and maybe a way to fix this.

Answer

Pass in data as a dictionary:

data = {
    'caption', caption,
    'access_token', token
}
files = {
    'file': open(IMG_PATH, 'rb')
}
status = requests.post(
    'https://graph.facebook.com/v2.7/PAGE_ID/photos',
     data=data, files=files)

requests can't produce multipart/form-data parts (together with the files you are uploading) from a application/x-www-form-urlencoded encoded string.

Using a dictionary for the POST data has the additional advantage that requests takes care of properly encoding the values; caption especially could contain data that you must escape properly.