I have frustrated with this problem I googled it and I didn't find a proper answer so decided to ask it here. I have the following classes
from fastapi import FastAPI, File, UploadFile, BackgroundTasks, Body
from pydantic import BaseModel
import shutil
import datetime
class UserIn(BaseModel):
username: str
password: str
family: str
age: int
height: float
gender: bool
usr = UserIn(username='Bob', password='123456', family='Foo', age=21, height=169, gender=True)
and the following route method
@app.post("/uploadfile/")
async def create_upload_file(background_tasks: BackgroundTasks, current_user: UserIn = Body(usr),
file: UploadFile = File(...)):
background_tasks.add_task(send_video_for_process, file, current_user)
return {"message": f"The {current_user.username} file {file.filename} uploaded"}
and the function is
def send_video_for_process(video: UploadFile, user: UserIn):
content = video.file
video_path = '/users/'
path = video_path + user.username + video.filename
with open(path, "wb") as buffer:
shutil.copyfileobj(content, buffer)
return 'Done!'
When I don't pass anything the method pass usr
correctly, but when I want to pass it with postman or docs of Fastapi. I am getting the following error.
{
"detail": [
{
"loc": [
"body",
"current_user"
],
"msg": "value is not a valid dict",
"type": "type_error.dict"
}
]}
the dictionary I put in postman is this {"username": "Alice","password": "abcd1234","family": "Hey","age": 19,"height": 160,"gender": False}
and here is a screenshot of my postman.
in the /docs I only change the value inside the schema but still get the same error.
I have added all libraries and I tried without Body(...)
version. I played a lot with the dictionary but I got nothing.
I don't want to use Form
or Query
. I need the benefit of BaseModel in the future.
I use Mac and my server is uvicorn
.
Any idea what is going on?
question from:
https://stackoverflow.com/questions/65910629/passing-dict-value-to-basemodel-via-postman-and-openapi-in-fastapi