I would like to send multiple images to FastAPI backend using Python requests.
Server side
from fastapi import FastAPI, UploadFile, File
from typing import List
app = FastAPI()
@app.post("/")
def index(file: List[UploadFile] = File(...)):
list_image = []
for i in file:
list_image.append(i.filename)
return {"list_image": list_image}
Client side
Currently, I can only send a request with a single image. However, I would like to be able to send multiple images.
import requests
import cv2
frame = cv2.imread("../image/3.png")
imencoded = cv2.imencode(".jpg", frame)[1]
file = {'file': ('image.jpg', imencoded.tostring(),
'image/jpeg', {'Expires': '0'})}
response = requests.post("http://127.0.0.1:8000/", files=file)
You would need to pass the files/images as shown in the example below. See here and here and here for more details.
import requests
url = 'http://127.0.0.1:8000/'
files = [('file', open('images/1.png', 'rb')), ('file', open('images/2.png', 'rb'))]
resp = requests.post(url=url, files=files)
or, you could also use:
import requests
import glob
path = glob.glob("images/*", recursive=True) # images' path
files = [('file', open(img, 'rb')) for img in path]
url = 'http://127.0.0.1:8000/'
resp = requests.post(url=url, files=files)