'How to POST multiple images to FastAPI server using Python requests?
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)
Solution 1:[1]
Use as below:
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |