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>This was the correct format:</p>

<pre><code>imgName = "tmp/graph.png"
files = { "filedata" : ('filename.png', open(imagePath, 'rb'), 'image/png')}   
data = {
    "recipient":'{"id":"' + id + '"}',
    "message":'{"attachment":{"type":"image", "payload":{}}}'
    }

r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=' + ACCESS_TOKEN, files=files, data=data)
</code></pre>

python facebook curl python-requests messenger