Using UploadFile and Pydantic model in one request

See original GitHub issue

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, UploadFile
from pydantic import BaseModel

app = FastAPI()


class Properties(BaseModel):
    language: str = None
    author: str = None


@app.post("/uploadfile/", status_code=201)
async def create_upload_file(properties: Properties, file: UploadFile = File(...)):
    return {"filename": file.filename, 'properties': properties}

Description

  • Open the browser /docs and call the endpoint /uploadfile.
  • It returns error 422 Validation Error.
  • But I expected it to return code 201.

Environment

  • OS: Linux (Fedora)
  • FastAPI Version: 0.61.1
  • Python version: 3.8.6

Additional context

Immediately I apologize, maybe I missed something and / or did not understand and should not have bothered you. I need this function in order to unload a poster for it along with information in the form of a Pydantic model. I issued a patch, but everyone ignores it

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:4
  • Comments:23 (2 by maintainers)

github_iconTop GitHub Comments

21reactions
SirTelemakcommented, Oct 28, 2020

Oups, sorry, I forgot I made custom validator to transform str to json for Model:

class Model(BaseModel):
    foo: int
    bar: str

    @classmethod
    def __get_validators__(cls):
        yield cls.validate_to_json

    @classmethod
    def validate_to_json(cls, value):
        if isinstance(value, str):
            return cls(**json.loads(value))
        return value
7reactions
Freestyle1190commented, Nov 13, 2020

Hi,

if I understand you well you can use UploadFile and Pydantic model in one request using Dependencies. More detailed information here: https://fastapi.tiangolo.com/tutorial/dependencies/ Sample code:

from fastapi import File, UploadFile, Depends

class User(BaseModel):

    username: str
    password: str

@app.post('/user')
async def upload(user: User = Depends(), file: UploadFile = File(...)):

  data_db = user.dict()
  print(data_db)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Pydantic params validation with file upload - Stack Overflow
You can either use Form(...) fields, Dependencies with Pydantic models, or send a JSON string using a Form field and then parse it,...
Read more >
How to use FastAPI UploadFile with Pydantic model
This is a short tutorial to guide you on how to use Pydantic models and UploadFile together in FastAPI. I had to figure...
Read more >
Create products and explore File upload handling
If you curious about this discussion please read on here -> Using UploadFile and Pydantic model in one request (opens new window) and...
Read more >
Request Files - FastAPI
UploadFile has the following async methods. They all call the corresponding file methods underneath (using the internal SpooledTemporaryFile ).
Read more >
Upload file & other data in a request : r/FastAPI - Reddit
I'm a bit surprised to see that it's not possible to use a Pydantic model for this (like that): class CreateItem(BaseModel): name: str ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found