I have an immutable Pydantic model (Item
) that requires a field shape_mode
that is schematic
or realistic
. The default value of the shape_mode
should depend on the response class:
- for
application/json
default isschematic
- for
image/png
default isrealistic
The question is: can I modify the field shape_mode
based on the accept
header, before the body is parsed to an Item
object?
from enum import Enum
from fastapi import FastAPI, Request
from pydantic import BaseModel
class ShapeModeEnum(str, Enum):
schematic = "schematic"
realistic = "realistic"
class Item(BaseModel):
name: str
shape_mode: ShapeModeEnum
class Config:
allow_mutation = False
extra = "forbid"
strict = True
validate_assignment = True
app = FastAPI()
RESPONSE_CLASSES = {
"application/json": "schematic",
"image/png": "realistic",
}
@app.post("/item")
async def create_item(
request: Request,
item: Item,
):
accept = request.headers["accept"]
return [item, accept]