Get response/return value after a POST request (python requests)

Viewed 4859

I am trying to send an image to my API and then get results back from it. For example I send a bmp image file using

file = {"img": open("img.bmp)}
r = requests.post(url, files = file)

Now I'm getting stuck on how to read the result from the API.

Usually we have a data value we send to API and get results as

data = {"data":"MyDataString"}
r = requests.get(url, params = data)

But I need to send an Image. I tried looking for ways to send image in a GET request or use r.content with the POST request but couldn't make it work.

For better visualizing the problem here is an example: Consider an API where you send an image and get the processed image in result.

Hopefully you can guide me in the right direction.

2 Answers

Here is a modification to your program that posts your program to a URL and is expecting a BMP image back and writes the output to stdout, which you could redirect to a disk file. The point, however, is that the returned image is the byte stream r.content. Do what you want with it.

import requests
import sys

url = 'some-url'
with open("img.bmp", "rb") as f:
    file = {"img": f}
    r = requests.post(url, files=file)
sys.stdout.buffer.write(r.content)

Here is an example of a Python CGI program at URL "some-url". This just returns the original BMP:

#!/usr/bin/env python3
import cgi
import cgitb
import sys

cgitb.enable()

form = cgi.FieldStorage()
fileitem = form['img']
bmp = fileitem.file.read()

print('Content-Type: img/bmp\r\n\r\n', end='', flush=True)
# just send back the original image unmodified
sys.stdout.buffer.write(bmp)

I found a way to do the job. ( Sending and receiving image with a POST request)

While sending the file with same method as in question's POST request I receive the resulting image as a base64 encoded string. I simply had to read it from r.content and decode.

To Debug I used httpbin.org as my url in POST request to see the data I was sending.

i.e r = requests.post("https://httpbin.org", files = file)

Solution For solving the problem I used the decode/encode methods according to this guide here

The answer by Booboo helped me to find this solution.

Hopefully this will help others.

Related