Use Request
instead of Pydantic model in POST
, but still document the pydanti model
#11473
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, Request
from pydantic import BaseModel
app = FastAPI()
class Foo(BaseModel):
bar: str
@app.post("/test")
async def test(req: Request):
body = await req.body().decode("utf-8")
# do stuff with body
parsed = Foo.model_validate_json(body)
# do stuff with parsed DescriptionIs there a way to still document Operating SystemLinux, macOS Operating System DetailsNo response FastAPI Version0.109.1 Pydantic Version2.3.0 Python Version3.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
I'm not aware of a way to achieve exactly what you're asking but you may want to try to switch |
Beta Was this translation helpful? Give feedback.
-
You can declare every path operation twice, but disable including in openapi schema for one of them. Only first operation will be executed
If you perform a post request to "/" it will print "real" in console, but in the documentation you will see documentation for But I'm not sure if this is a good approach. I assume that this behavior may be changed in the future.. |
Beta Was this translation helpful? Give feedback.
-
one way to solve your problem is to define openapi specs separately with custom openapi schema on routers. from fastapi import FastAPI, Request
from pydantic import BaseModel
app = FastAPI()
class Foo(BaseModel):
bar: str
@app.post(
"/test",
openapi_extra={
"requestBody": {
"content": {
"application/json": {
"schema": Foo.schema()
}
},
"required": True,
},
},
)
async def test(req: Request):
body = await req.body()
body = body.decode("utf-8")
parsed = Foo.model_validate_json(body) |
Beta Was this translation helpful? Give feedback.
-
Thanks both of you guys! These both work - I ended up going with @YuriiMotov 's approach since that one guarantees the schema will be the exact same as what I had before. |
Beta Was this translation helpful? Give feedback.
You can declare every path operation twice, but disable including in openapi schema for one of them. Only first operation will be executed