Reputation: 184
I'm trying upload user data with file. I wanna do something like this, validate user data and attach file
class User(BaseModel):
user: str
name: str
@router.post("/upload")
async def create_upload_file(data: User, file: UploadFile = File(...)):
print(data)
return {"filename": file.filename}
but it doesn't work Error: Unprocessable Entity Response body:
{
"detail": [
{
"loc": [
"body",
"data"
],
"msg": "value is not a valid dict",
"type": "type_error.dict"
}
]
}
But if i do separate ulr all work:
class User(BaseModel):
user: str
name: str
@router.post("/d")
async def create(file: UploadFile = File(...)):
return {"filename": file.filename}
@router.post("/")
def main(user: User):
return user
How to combine all together?
Upvotes: 8
Views: 13250
Reputation: 34551
You can't declare Body
fields that you expect to receive as JSON
along with Form
fields, as the request will have the body encoded using application/x-www-form-urlencoded
(or multipart/form-data
, if files are included), instead of application/json
.
You can either use Form(...)
fields, Dependencies
with Pydantic models, or send a JSON
string using a Form
field and then parse it, as described in this answer.
Upvotes: 2
Reputation: 2380
You can't have them at the same time, since pydantic models validate json
body but file uploads is sent in form-data
.
So they can't be used together.
If you want to do it you should do a trick.
Please check out this link to know how to use pydantic models in form data.
Upvotes: 0