Download a file via a POST request

Viewed 8332

I have an API endpoint that dynamically generates an image based on some pass data. I would like to call the API and download the response into a file. What's the best way to accomplish this in Python?

The request looks like this in cURL:

curl https://localhost:4000/bananas/12345.png \
  -O \
  -X POST \
  -d '[ 1, 2, 3, 4 ]'
2 Answers

You should use requests package instead of executing curl or other processes:

import requests

response = requests.post('https://localhost:4000/bananas/12345.png', data = '[ 1, 2, 3, 4 ]')
data = response.content

data contains the downloaded content after that, which you can store to disk for instance:

with open(path, 'wb') as s:
    s.write(data)

I'd prefer subprocess over os.system any day, so here's the equivalent:

import subprocess

_CURL_POST = "curl https://localhost:4000/bananas\
/12345.png \
-O \
-X POST \
-d '[ 1, 2, 3, 4 ]'
"

subprocess.call(_CURL_POST)
Related