Bug: OpenAPI schema inaccuracies (responses content, Pydantic Query models, ValidationError.msg, x- extensions, Path alias, Decimal NaN)
Expected Behaviour
The generated OpenAPI schema matches what the resolver validates and returns.
Current Behaviour
Six schema inaccuracies:
responses={404: {"description": "nf"}}withoutcontentgets the handler's return model injected for every status code (openapi/schema_generator.py:506). A 404 documented as description-only is published as returning the model.- A Pydantic model used as
Query()/Header():int | None,list[str]and Enum fields come out as{"type": "string"}(schema_generator.py:373,issubclass(Union, int)raises and falls back to string). Validation is correct, only the schema is wrong. - The
ValidationErrorcomponent requiresmsg, which is neither inpropertiesnor in the real 422 body (openapi/types.py:28). Every 422 response violates the published schema. openapi_extensionsat root (api_gateway.py:1813) and operation level (schema_generator.py:403) skip thex-prefix check thatServerandSecuritySchemeenforce.Path(alias="ident")can never be satisfied (422 missing,openapi_validation.py:422looks upfield.aliasbut route args are keyed by the template name) and emits a parameter name not in the path template.Decimal("NaN")orDecimal("Infinity")in a response raisesTypeError: '>=' not supported between 'str' and 'int'instead ofSerializationError(openapi/encoders.py:330).
Code snippet
import decimal, json
from typing import Annotated
from pydantic import BaseModel
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.openapi.params import Path, Query
from tests.functional.utils import load_event
class Todo(BaseModel):
id: int
class Q(BaseModel):
limit: int | None = None
tags: list[str] = []
app = APIGatewayRestResolver(enable_validation=True)
@app.post("/resp", responses={200: {"description": "ok", "content": {"application/json": {"model": Todo}}}, 404: {"description": "nf"}})
def resp() -> Todo: return Todo(id=1)
@app.get("/qm")
def qm(q: Annotated[Q, Query()]): return {}
@app.get("/pa/<id>", openapi_extensions={"foo": "bar"})
def pa(id: Annotated[int, Path(alias="ident")]): return {"id": id}
@app.get("/nf")
def nf(): return {"x": decimal.Decimal("NaN")}
s = json.loads(app.get_openapi_json_schema(openapi_extensions={"foo": "bar"}))
print(s["paths"]["/resp"]["post"]["responses"]["404"]) # has content -> Todo
print([(p["name"], p["schema"]) for p in s["paths"]["/qm"]["get"]["parameters"]]) # all "string"
print(s["components"]["schemas"]["ValidationError"]["required"]) # ['loc', 'msg', 'type']
print("foo" in s, "foo" in s["paths"]["/pa/{id}"]["get"]) # True True
ev = load_event("apiGatewayProxyEvent.json")
ev["path"] = "/pa/12"; print(app.resolve(ev, None)["statusCode"]) # 422
ev["path"] = "/nf"; app.resolve(ev, None) # TypeError
Possible Solution
Only fill content from the return type when resp_code == status_code; build field schemas with TypeAdapter(annotation).json_schema(); drop msg from required; validate the x- prefix in both places; look up path params by field.name or reject alias on Path; check Decimal.is_finite() and raise SerializationError.
Steps to Reproduce
Run the snippet above with the tests/events fixtures. Full context in #8576.
Powertools for AWS Lambda (Python) version
latest
AWS Lambda function runtime
3.13
Packaging format used
PyPi
Debugging logs
[!WARNING] This issue is ready to be picked up, by humans or by agents. If you want it, comment here first so we can assign it to you, and please take only one or two issues at a time so others can join in too. Thanks!
Taking this up — will open a PR shortly.
Hey @SpinachDigital pls go ahead, I saw #8630. Will review.
[!warning] This issue is now closed. Please be mindful that future comments are hard for our team to see. If you need more assistance, please either reopen the issue, or open a new issue referencing this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.
This is now released under 3.39.0 version!