Python: curl -F equivalent with Requests or other
<p>I want to reproduce the following curl -F request (<a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment" rel="nofollow">from the Messenger API</a>) to send an image file and parameters to Messenger's Send API:</p>

<pre><code>curl  \
-F recipient='{"id":"USER_ID"}' \
-F message='{"attachment":{"type":"image", "payload":{}}}' \
-F filedata=@/tmp/shirt.png \
"https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"
</code></pre>

<p>I'm using Requests and I tried many, many things (including with correct recipient IDs, etc.. For instance:</p>

<pre><code>recipient = '{"id":"USER_ID"}'
message = '{"attachment":{"type":"image", "payload":{}}}'
files = [("recipient", recipient), ("message", message), ("filedata", open(imagePath, 'rb'))]
r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN', files=files)
</code></pre>

<p>I also tried:</p>

<pre><code>files = {"recipient" : recipient, "message" : message, "filedata" : open(imagePath, "rb")}
</code></pre>

<p>I almost always get this response error from Messenger:</p>

<pre><code>'{"error":{"message":"(#100) param recipient must be non-empty.","type":"OAuthException","code":100,"fbtrace_id":"xxxxx"}}'
</code></pre>

<p>I'm at a loss here. I'm probably misusing the Requests syntax somehow, or sending a poorly formatted string to the API, but I've read the Requests documentation and browsed through StackOverflow's questions on this and couldn't solve my issue. Thank you.</p>

<p>I believe the issue is that you are trying to send formdata inside the requests file kwarg, when it should be in data:</p>

<pre><code>data = {
    'recipient': '{"id":"USER_ID"}',
    'message': '{"attachment":{"type":"image", "payload":{}}}'
}
files = {
    "filedata": open(imagePath, 'rb')
}
r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN', data=data, files=files)
</code></pre>

<p>The one assumption is that imagePath exists.</p>

<p>Also in python <code>{}</code> denotes a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">Set</a> if it doesn't have <code>key:value</code> pairs in it, so in your answer, you are passing a Set of a single tuple, which has two items in it, the string <code>filedata</code> and a <code>file object</code>.</p>

<pre><code>{("filedata", open(imgName, 'rb'))} # Set of tuple
{"filedata": open(imgName, 'rb')}   # dictionary
</code></pre>

python facebook curl python-requests messenger