diff --git a/docs/core/event_handler/api_gateway.md b/docs/core/event_handler/api_gateway.md index 8740c264c46..1ca54ac57b4 100644 --- a/docs/core/event_handler/api_gateway.md +++ b/docs/core/event_handler/api_gateway.md @@ -874,6 +874,13 @@ You can use the `Response` class to have full control over the response. For exa --8<-- "examples/event_handler_rest/src/fine_grained_responses_output.json" ``` +???- note "Using `Response` with data validation?" + When using the [data validation](#data-validation) feature with `enable_validation=True`, you must specify the concrete type for the `Response` class. This allows the validation middleware to infer the underlying type and perform validation correctly. + + ```python hl_lines="8 26 32" + --8<-- "examples/event_handler_rest/src/data_validation_fine_grained_response.py" + ``` + ### Compress You can compress with gzip and base64 encode your responses via `compress` parameter. You have the option to pass the `compress` parameter when working with a specific route or using the Response object. diff --git a/examples/event_handler_rest/src/data_validation_fine_grained_response.py b/examples/event_handler_rest/src/data_validation_fine_grained_response.py new file mode 100644 index 00000000000..1209c6a1af1 --- /dev/null +++ b/examples/event_handler_rest/src/data_validation_fine_grained_response.py @@ -0,0 +1,39 @@ +from http import HTTPStatus +from typing import Optional + +import requests +from pydantic import BaseModel, Field + +from aws_lambda_powertools import Logger, Tracer +from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response, content_types +from aws_lambda_powertools.logging import correlation_paths +from aws_lambda_powertools.utilities.typing import LambdaContext + +tracer = Tracer() +logger = Logger() +app = APIGatewayRestResolver(enable_validation=True) + + +class Todo(BaseModel): + userId: int + id_: Optional[int] = Field(alias="id", default=None) + title: str + completed: bool + + +@app.get("/todos/") +@tracer.capture_method +def get_todo_by_id(todo_id: int) -> Response[Todo]: + todo = requests.get(f"https://jsonplaceholder.typicode.com/todos/{todo_id}") + todo.raise_for_status() + return Response( + status_code=HTTPStatus.OK.value, + content_type=content_types.APPLICATION_JSON, + body=todo.json(), + ) + + +@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST) +@tracer.capture_lambda_handler +def lambda_handler(event: dict, context: LambdaContext) -> dict: + return app.resolve(event, context)