litestar-org/litestar
在 GitHub 查看Enhancement: Support for Typing the `query` keyword (and other reserved kwargs) to generate OpenAPI Spec
Open
#2,015 建立於 2023年7月20日
EnhancementGood First IssueHelp Wanted :sos:OpenAPI
描述
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?