[Python] How to use "WithJsonSchema" and annotated types when defining query params

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    Example path operations:

    # Types
    ParamAnnotated = Annotated[
    str,
    WithJsonSchema({"type": "string", "enum": ['v1', "v2"], "title": "ParamAnnotated"}),
    ]

    class ParamEnum(Enum):
    V1 = 'v1'
    V2 = 'v2'


    # APP
    app = FastAPI()
    @app.get("/get1")
    async def _get(request: Request, param_annotated:paramAnnotated, param_enum: ParamEnum):
    pass


    "param_annotated" missing "enum" key from generated openapi.json.

    "parameters": [
    {
    "name": "param_annotated",
    "in": "query",
    "required": true,
    "schema": {
    "type": "string",
    ##### enum key/value missing
    "title": "Param Annotated"
    }
    },
    {
    "name": "param_enum",
    "in": "query",
    "required": true,
    "schema": {
    "type": "string",
    "enum": ["v1","v2"],
    "title": "ParamEnum"
    }
    }
    ],


    No issue when using ParamAnnotated in a "post" path operation:

    class TestModel(BaseModel):
    param_annotated: ParamAnnotated
    param_enum: ParamEnum


    @app.post("/post1")
    def _post1(request: Request, payload: TestModel) -> dict:
    pass


    openapi.json now has the "enum" key:

    "param_annotated": {
    "type": "string",
    "enum": [
    "v1",
    "v2"
    ],
    "title": "ParamAnnotated"
    }....


    Goal is to share "TestModel" across path operations (see below) without creating 2 separate models:

    async def _get(request: Request, query_params: TestModel = Depends()):
    pass

    @app.post("/post1")
    def _post1(request: Request, payload: TestModel) -> dict:
    pass

    Continue reading...

Compartilhe esta Página