bytes field inside Pydantic model with Form() fails — UploadFile not read
#15098
-
First Check
Commit to Help
Example Codefrom typing import Annotated
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class UploadForm(BaseModel):
name: str
file: bytes
@app.post("?url=https%3A%2F%2Fgithub.com%2Fupload%2F")
async def upload(data: Annotated[UploadForm, Form()]):
return {"name": data.name, "size": len(data.file)}
client = TestClient(app)
response = client.post(
"?url=https%3A%2F%2Fgithub.com%2Fupload%2F",
files={"file": ("test.txt", b"hello world", "text/plain")},
data={"name": "test"},
)
print(response.status_code)
print(response.json())
---DescriptionOperating System:FastAPI Version:The standalone I also checked that I have looked at the source code and I believe I can fix this. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Declaring file upload fields using Pydantic model is not officially supported (see comment to closed PR). To make your example work, you need to add class UploadForm(BaseModel):
name: str
file: Annotated[bytes, File()]And specify @app.post("?url=https%3A%2F%2Fgithub.com%2Fupload%2F")
async def upload(data: Annotated[UploadForm, Form(media_type="application/x-www-form-urlencoded")]):
return {"name": data.name, "size": len(data.file)}One more time: this is not officially supported. You can use it on your own risk) |
Beta Was this translation helpful? Give feedback.
Declaring file upload fields using Pydantic model is not officially supported (see comment to closed PR).
To make your example work, you need to add
File()annotation tofilefield:And specify
media_type="application/x-www-form-urlencoded"as follows to make schema correct:One more time: this is not officially supported. You can use it on your own risk)