is there a way to send multiple images to an API at the same time fastapi

Viewed 1207

I need to hit the fastapi with multiple images

@app.post("/text")
def get_text(files: List[UploadFile] = File(...)):

its working when I try uploading multiple images using /docs interface, I tried with one file its working fine here is the code for it

import requests
import json
def get_text(image_path):
    #images={}
    url = 'http://address/text'
    try:
        with open(image_path, "rb") as im:
            image_data={"files":im}
            response=requests.post(url,files=image_data)
            return json.loads(response.text)
    except Exception as er:
        print("error occured")
        return "{} error occured".format(er)

when I tried adding more images to the image_data but i am getting error.

image_data ={"files":[]}
for image in image_list:
    with open(image, "rb") as im:
        image_data['files'].append(im)

tried above code but no use.

error message after running the above error message

1 Answers

I finally found the solution , its not the problem of fastapi , its related to requests library

Incase any one needs the solution here it is

files = [
        ('files', ('image1', open('/Users/ai/image1.jpg','rb'), 'image/png')),
        ('files', ('image2', open('/Users/ai/image2.jpeg','rb'), 'image/png'))
        ]

you can use the below function for multiple files

import requests
import json

def get_text(image_list,url):
    try:
        image_data=[]
        for image in image_list:
            image_data.append(('files',(image.split('/')[-1],open(image,'rb'),'image/png')))#('files',(image_name,open image,type))
        response=requests.post(url,files=image_data)
        return json.loads(response.text)
    except Exception as er:
        print("error occured")
        return "{} error occured".format(er)

You can check docs Here

Thanks..!

Related