In dependency get_service
I want to decide by request_type_code
which of two services to choose:
from typing import Annotated, Literal
from uuid import UUID
from fastapi import FastAPI, Body, Depends
from pydantic import BaseModel, Field, RootModel
app = FastAPI()
class ProlongService:
pass
class InclusService(ProlongService):
pass
def get_service(request_type_code: str = Body()): # does not work
if request_type_code == "inclus":
return InclusService()
return ProlongService()
class ProlongSchema(BaseModel):
attachment_ids: list[UUID]
partner_id: UUID
request_type_code: Annotated[Literal["prolong"], Field(...)]
class InclusSchema(ProlongSchema):
region_codes: list[str]
request_type_code: Annotated[Literal["inclus"], Field(...)]
class CreateSchema(RootModel):
root: Annotated[InclusSchema | ProlongSchema, Field(..., discriminator="request_type_code")]
@app.post("/create")
async def create(data: CreateSchema, service: InclusService | ProlongService = Depends(get_service)):
pass
The code above gives wrong swagger schema:
Keys inside data
should be one the same level as request_type_code
.
How to retrieve only request_type_code
into get_service
dependency?