3

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 ]'
LandonSchropp
  • 10,084
  • 22
  • 86
  • 149

2 Answers2

8

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)
clemens
  • 16,716
  • 11
  • 50
  • 65
  • 1
    Sorry, I'm a Python newbie here. Would `data` contain the binary content of the file, or does Python assume a default encoding? Also, how would I write the response content to a file? – LandonSchropp Nov 20 '17 at 07:32
  • @LandonSchropp Most of these questions, including your original, could've been answered with a little google searching... so I recommend you get on that... – cs95 Nov 20 '17 at 07:33
  • Yes, it will be a byte array. I've added an example how to save to disk. – clemens Nov 20 '17 at 07:36
  • Thank you for the quick answer! – LandonSchropp Nov 20 '17 at 07:42
  • @cs95 oddly enough google returns this page as a result when searching. I think a lot of people use stackoverflow as a first choice in their results, and I would imagine that stackoverflow benefits from the traffic. – Clyde Jan 20 '23 at 19:22
-2

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)
Daniel
  • 769
  • 8
  • 21
  • 2
    Python has libs for doing URL requests. Executing subprocesses is a very bad solution. – clemens Nov 20 '17 at 07:25
  • 1
    `Please add your suggestions as new answer :)` This was bad advice, you shouldn't have taken it. There's no better way to do this than using a standard library for the task, rather than making subprocess calls. – cs95 Nov 20 '17 at 07:29