5

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?

  • 1
    Related topic https://stackoverflow.com/questions/65504438/how-to-add-both-file-and-json-body-in-a-fastapi-post-request – alex_noname Nov 13 '21 at 05:36

2 Answers2

1

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.

Chris
  • 18,724
  • 6
  • 46
  • 80
0

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.

Mojtaba Arezoomand
  • 2,140
  • 8
  • 23