Thanks to visit codestin.com
Credit goes to github.com

Skip to content

multipart/form-data: Object parsing error when using files and object in request form #2365

@tricosmo

Description

@tricosmo

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here's a self-contained, minimal, reproducible, example with my use case:

from fastapi import FastAPI, File, Form
from pydantic import BaseModel

app = FastAPI()


class Address(BaseModel):
    first_line: str
    post_code: str


class User(BaseModel):
    first_name: str
    last_name: str
    address: Address


@app.post("/users/")
async def create_user(avatar: bytes = File(...), user: User = Form(...)):
    return {
        "file_size": len(avatar),
        "user": user,
    }


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host='0.0.0.0', port=8000, debug=True)

Description

  • Open the browser and call the endpoint /docs. Click try it out on the API
  • upload a file, click execute
  • It returns error with status 422 Unprocessable Entity
{
  "detail": [
    {
      "loc": [
        "body",
        "user"
      ],
      "msg": "value is not a valid dict",
      "type": "type_error.dict"
    }
  ]

.

Environment

  • OS: "Ubuntu 18.04.5 LTS"

  • pip
    fastapi==0.61.2
    python-multipart==0.0.5
    requests==2.24.0
    starlette==0.13.6
    uvicorn==0.12.1
    ...

  • Python version: 3.8.6

Additional context

I found #842 has similar issue, this one is more a mixed use of files and object in a form data.

Not sure if I messed something up, but thanks for any advice.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions