Example
Here's my code trying to upload a list of images:
import requests
import glob
import cv2
path = glob.glob("test_folder/*", recursive=True) # a list of image's path
lst_img = []
for p in path[:3]:
# img = cv2.imread(p)
lst_img.append((p, open(p, 'rb'), "image/jpeg"))
data = {"files": lst_img}
url = "http://localhost:6789/" # url api of app
res = requests.post(url=url, data=data)
print(res.status_code)
print(res.text)
Description
I am trying to upload a list of images through Python requests (package) to a FastAPI endpoint, but maybe my request's format is wrong, leading to a 422
error:
"detail":[{"loc":["body","files",0],"msg":"Expected UploadFile, received: <class 'str'>","type":"value_error"}
This is my request's format:
{'files': [('test_folder/image77.jpeg', <_io.BufferedReader name='test_folder/image77.jpeg'>, 'image/jpeg'), ('test_folder/image84.jpeg', <_io.BufferedReader name='test_folder/image84.jpeg'>, 'image/jpeg'), ('test_folder/image82.jpeg', <_io.BufferedReader name='test_folder/image82.jpeg'>, 'image/jpeg')]}
I've tried many ways, but always fails. Many thank if u guys help to solve it.
Environment
- OS: Linux: (Ubuntu 18.04)
- FastAPI Version: 0.61.1
- Requests Version: 2.24.0
- Python Version: 3.7.5
I tried the below, but still not working:
lst_img.append(("file", (p, open(p, 'rb'), "image/jpeg")))
My FastAPI main.py
from typing import List
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import StreamingResponse, FileResponse
app = FastAPI()
@app.post("/")
async def main(files: List[UploadFile] = File(...)):
# file_like = open(video_path, mode="rb")
# return StreamingResponse(file_like, media_type="video/mp4")
return {"filenames": [file.filename for file in files]}