Skip to content

Bug: Broken behaviour for setting alias in Query Annotated Field after pydantic 2.12.0 update #7552

@migrund

Description

@migrund

Expected Behaviour

When defining a Annotated Query Field it should behave in the same way as pydantic does (set validation_alias the same as alias if not set otherwise).

This issue was reported in pydantic (#12369) before. I was told that this is an issue how powertools-lambda-python implements the FieldInfo.
It is related to this topic in pydantic (#12374)

Current Behaviour

The validation_alias attribute is not set if not explicitly defined.

Code snippet

from __future__ import annotations

from http import HTTPStatus
from typing import Annotated
from typing import Any
from unittest.mock import MagicMock

from annotated_types import Ge
from annotated_types import Le
from aws_lambda_powertools.event_handler.api_gateway import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.api_gateway import Response
from aws_lambda_powertools.event_handler.openapi.params import Query
from aws_lambda_powertools.utilities.typing import LambdaContext
from pydantic import StringConstraints
from pydantic import validate_call

app = APIGatewayRestResolver(
    strip_prefixes=["/my-service"],
    enable_validation=True,
)

type IntQuery = Annotated[int, Ge(1), Le(100)]
type StrQuery = Annotated[str, StringConstraints(min_length=4, max_length=128)]


def handler(event: dict[str, Any], context: LambdaContext) -> dict[str, Any]:
    return app.resolve(event, context)


@app.get("/foo")
def get_foo(
    # With pydantic v2.11.9: PydanticValidation and PowertoolsValidation tests successful
    # With pydantic v2.12.0: PydanticValidation test fails with ValidationError, PowertoolsValidation test successful
    str_query: Annotated[StrQuery, Query(alias="strQuery")],
    int_query: Annotated[IntQuery, Query(alias="intQuery")],
    #
    # With pydantic v2.11.9: PydanticValidation and PowertoolsValidation tests fail with ValidationError
    # With pydantic v2.12.0: PydanticValidation test successful, PowertoolsValidation test fails with ValidationError
    # str_query: Annotated[StrQuery, Query(validation_alias="strQuery")],
    # int_query: Annotated[IntQuery, Query(validation_alias="intQuery")],
    #
    # With pydantic v2.11.9: PydanticValidation and PowertoolsValidation tests successful
    # With pydantic v2.12.0: PydanticValidation and PowertoolsValidation tests successful
    # str_query: Annotated[StrQuery, Query(alias="strQuery", validation_alias="strQuery")],
    # int_query: Annotated[IntQuery, Query(alias="intQuery", validation_alias="intQuery")],
) -> Response[str]:
    return Response(HTTPStatus.OK, content_type="plain/text", body=f"{int_query}, {str_query}")


class TestPydanticValidation:
    def test__valid_parameters_given__success_expected(self):
        # GIVEN
        valid_parameters = dict(intQuery=20, strQuery="fooBarFizzBuzz")

        # WHEN
        result = validate_call(get_foo)(**valid_parameters)

        # THEN
        assert result.body == "20, fooBarFizzBuzz"


class TestPowertoolsValidation:
    def test__valid_parameters_given__success_expected(self):
        # GIVEN
        api_gateway_proxy_event = {
            "httpMethod": "GET",
            "path": "/my-service/foo",
            "multiValueQueryStringParameters": {
                "intQuery": ["20"],
                "strQuery": ["fooBarFizzBuzz"],
            },
        }

        # WHEN
        response = handler(api_gateway_proxy_event, MagicMock())

        # THEN
        assert response["body"] == "20, fooBarFizzBuzz"
        assert response["statusCode"] == HTTPStatus.OK

Possible Solution

No response

Steps to Reproduce

In the above code snippet (un-)comment str_query and int_query depending on the pydantic version and the use-case.

Powertools for AWS Lambda (Python) version

latest

AWS Lambda function runtime

3.13

Packaging format used

PyPi

Debugging logs

Metadata

Metadata

Type

Projects

Status

Pending customer

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions