I am trying to submit form-data with a Pydantic model.
from dataclasses import dataclass
from typing import Annotated
from fastapi import FastAPI, Form, Depends, Response, status
from pydantic import BaseModel
class SimpleModel(BaseModel):
title: str = Form(...)
content: str = Form(...)
@dataclass
class SimpleDataclass:
title: str = Form(...)
content: str = Form(...)
app = FastAPI()
@app.post("/post", status_code=status.HTTP_201_CREATED)
def create_post(request: SimpleModel = Depends()):
return Response(status_code=201)
@app.post("/post2", status_code=status.HTTP_201_CREATED)
def create_post(request: SimpleDataclass = Depends()):
return Response(status_code=201)
/post
takes a Pydantic BaseModel but it treats as query params, not form-data. Then I replace SimpleModel
by SimpleDataclass
and I got /post2
, this works as expected.
The question is why BaseModel
doesn’t work for me? I can’t use dataclass
so is there a way to make it work with BaseModel
?