Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions aws_lambda_powertools/event_handler/openapi/schema_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def generate_openapi_path(
"""
Generate the OpenAPI path spec and definitions for a single route.
"""
from aws_lambda_powertools.event_handler.openapi.dependant import get_flat_params
from aws_lambda_powertools.event_handler.openapi.dependant import get_flat_params, get_path_param_names

definitions: dict[str, Any] = {}

Expand All @@ -91,6 +91,7 @@ def generate_openapi_path(
all_route_params=all_route_params,
model_name_map=model_name_map,
field_mapping=field_mapping,
path_param_names=get_path_param_names(openapi_path),
)

if parameters:
Expand Down Expand Up @@ -162,6 +163,7 @@ def _build_operation_parameters(
all_route_params: Sequence[ModelField],
model_name_map: dict[TypeModelOrEnum, str],
field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
path_param_names: set[str],
) -> list[dict[str, Any]]:
"""Build the list of OpenAPI operation parameters."""
from aws_lambda_powertools.event_handler.openapi.params import Param
Expand All @@ -176,7 +178,7 @@ def _build_operation_parameters(
if _is_pydantic_model_param(field_info):
generated_parameters = _expand_pydantic_model_parameters(field_info)
else:
generated_parameters = [_create_regular_parameter(param, model_name_map, field_mapping)]
generated_parameters = [_create_regular_parameter(param, model_name_map, field_mapping, path_param_names)]

parameters.extend(
parameter
Expand Down Expand Up @@ -339,10 +341,18 @@ def _create_pydantic_field_parameter(
return individual_param


def _resolve_parameter_name(param: ModelField, field_info: Param, path_param_names: set[str]) -> str:
"""Resolve the OpenAPI parameter name, aligning path parameters with route-template placeholders."""
if field_info.in_.value == "path" and param.alias not in path_param_names and param.name in path_param_names:
return param.name
return param.alias


def _create_regular_parameter(
param: ModelField,
model_name_map: dict[TypeModelOrEnum, str],
field_mapping: dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
path_param_names: set[str],
) -> dict[str, Any]:
"""Create an OpenAPI parameter from a regular ModelField."""
from aws_lambda_powertools.event_handler.openapi.compat import get_schema_from_model_field
Expand All @@ -355,13 +365,8 @@ def _create_regular_parameter(
field_mapping=field_mapping,
)

# Path parameter names must match the route-template placeholders, which are
# keyed by the Python argument name - an explicit alias would otherwise emit
# a name that does not exist in the path template.
param_name = param.name if field_info.in_.value == "path" else param.alias

parameter: dict[str, Any] = {
"name": param_name,
"name": _resolve_parameter_name(param, field_info, path_param_names),
"in": field_info.in_.value,
"required": param.required,
"schema": param_schema,
Expand Down
80 changes: 80 additions & 0 deletions tests/functional/event_handler/_pydantic/test_openapi_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
Header,
Param,
ParamTypes,
Path,
Query,
_create_model_field,
)
Expand Down Expand Up @@ -1743,3 +1744,82 @@ def handler():
validation_error = schema["components"]["schemas"]["ValidationError"]
assert validation_error["required"] == ["loc", "type"]
assert "msg" not in validation_error["properties"]


def test_openapi_path_param_alias_matches_route_template():
# GIVEN a snake_case Python argument using Path(alias=...) to match a camelCase route placeholder
app = APIGatewayRestResolver(enable_validation=True)

@app.get("/P/<camelId>")
def get_p(snake_id: Annotated[str, Path(alias="camelId")]):
return {"id": snake_id}

@app.get("/Q/<camelId>")
def get_q(camelId: Annotated[str, Path()]):
return {"id": camelId}

# WHEN we generate the OpenAPI schema
schema = json.loads(app.get_openapi_json_schema())

# THEN both operations emit the route-template placeholder name in their path parameters
p_params = schema["paths"]["/P/{camelId}"]["get"]["parameters"]
q_params = schema["paths"]["/Q/{camelId}"]["get"]["parameters"]
assert [(p["name"], p["in"], p["required"]) for p in p_params] == [("camelId", "path", True)]
assert [(p["name"], p["in"], p["required"]) for p in q_params] == [("camelId", "path", True)]


def test_openapi_path_param_validation_alias_matches_route_template():
# GIVEN a path parameter using validation_alias to match the route placeholder
app = APIGatewayRestResolver(enable_validation=True)

@app.get("/orders/<orderId>")
def get_order(order_id: Annotated[str, Path(validation_alias="orderId")]):
return {"order_id": order_id}

# WHEN we generate the OpenAPI schema
schema = json.loads(app.get_openapi_json_schema())

# THEN the path parameter name matches the route placeholder
params = schema["paths"]["/orders/{orderId}"]["get"]["parameters"]
assert [p["name"] for p in params] == ["orderId"]


def test_openapi_path_param_alias_preserved_when_neither_matches_template():
# GIVEN a path parameter where neither the Python argument name nor the alias matches the route template
app = APIGatewayRestResolver(enable_validation=True)

@app.get("/items/<item_id>")
def get_item(other_id: Annotated[str, Path(alias="customId")]):
return {"id": other_id}

# WHEN we generate the OpenAPI schema
schema = json.loads(app.get_openapi_json_schema())

# THEN the explicit alias is preserved rather than falling back to an equally non-matching argument name
params = schema["paths"]["/items/{item_id}"]["get"]["parameters"]
assert [p["name"] for p in params] == ["customId"]


def test_openapi_path_param_alias_with_included_router_prefix():
# GIVEN a Router mounted under a dynamic prefix where handler arguments use Path(alias=...)
app = APIGatewayRestResolver(enable_validation=True)
router = Router()

@router.get("/items/<itemId>")
def get_item(
org_id: Annotated[str, Path(alias="orgId")],
item_id: Annotated[int, Path(alias="itemId")],
):
return {"org_id": org_id, "item_id": item_id}

app.include_router(router, prefix="/orgs/<orgId>")

# WHEN we generate the OpenAPI schema and invoke the route
schema = json.loads(app.get_openapi_json_schema())
result = app({"resource": "/orgs/{orgId}/items/{itemId}", "path": "/orgs/acme/items/7", "httpMethod": "GET"}, {})

# THEN schema parameters match both route placeholders and runtime validation succeeds
params = schema["paths"]["/orgs/{orgId}/items/{itemId}"]["get"]["parameters"]
assert [p["name"] for p in params] == ["orgId", "itemId"]
assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"org_id": "acme", "item_id": 7}
Original file line number Diff line number Diff line change
Expand Up @@ -4737,3 +4737,28 @@ def hello(headers: Annotated[HeaderModel, Header()]):

assert result["statusCode"] == 200
assert json.loads(result["body"]) == {"c": ["US", "PT"]}


def test_validate_path_param_alias_matches_route_template(gw_event):
# GIVEN a route placeholder in camelCase bound to a snake_case argument via Path(alias=...)
app = APIGatewayRestResolver(enable_validation=True)

@app.get("/users/<userId>")
def get_user(user_id: Annotated[int, Path(alias="userId")]):
return {"user_id": user_id}

# WHEN a valid request and an invalid request are resolved
gw_event["httpMethod"] = "GET"
gw_event["path"] = "/users/42"
valid_result = app(gw_event, {})

gw_event["path"] = "/users/not-an-int"
invalid_result = app(gw_event, {})

# THEN runtime validation resolves by alias and the OpenAPI schema emits the matching alias
assert valid_result["statusCode"] == 200
assert json.loads(valid_result["body"]) == {"user_id": 42}
assert invalid_result["statusCode"] == 422
assert json.loads(invalid_result["body"])["detail"][0]["loc"] == ["path", "userId"]
parameters = app.get_openapi_schema().paths["/users/{userId}"].get.parameters
assert [p.name for p in parameters] == ["userId"]
Loading