litestar-org/litestar

Enhancement: Support for Typing the `query` keyword (and other reserved kwargs) to generate OpenAPI Spec

开放

#2,015 创建于 2023年7月20日

 (17 条评论) (9 个反应) (0 位负责人)Python (550 个派生)user submission
EnhancementGood First IssueHelp Wanted :sos:OpenAPI

仓库指标

星标
 (8,243 个星标)
PR 合并指标
 (平均合并 13小时 27分钟) (30 天内合并 26 个 PR)

描述

Summary

Litestar supports query parameters that are validated as Pydantic models. As seen in the code under "Basic Example", validation of query parameters do indeed work as per the constraints set in the Pydantic model. While the route works as intended, the OpenAPI schema generated has no query parameters.

  "paths": {
    "/": {
      "get": {
        "summary": "Foo",
        "operationId": "Foo",
        "responses": {
          "200": {
            "description": "Request fulfilled, document follows",
            "headers": {},
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EvenOdd"
                }
              }
            }
          }
        },
        "deprecated": false
      }
    }
  }

Basic Example

from typing import Annotated
from litestar import Litestar, get
from pydantic import BaseModel, Field


class EvenOdd(BaseModel):
    even: Annotated[str, Field(regex=r"^\d*[02468]$")]
    odd: Annotated[str, Field(regex=r"^\d*[13579]$")]


@get()
async def foo(query: EvenOdd) -> EvenOdd:
    return query


app = Litestar([foo])


from litestar.testing import TestClient

with TestClient(app) as test:
    data = {'even': 0, 'odd': 1}
    response = test.get('', params=data)
    # query parameter validation works as expected
    assert response.status_code == 200

    data = {'even': 1, 'odd': 0}
    response = test.get('', params=data)
    # query parameter validation fails as expected
    assert response.status_code == 400
    assert 'Validation failed for GET' in response.json()['detail']

Drawbacks and Impact

Users who are migrating from other frameworks could expect the same behavior.

Unresolved questions

There is no "parameters" present in the schema. Is this intended behavior, or can the schema generation be changed so that "pydantic models as query parameters" work?

贡献者指南