Skip to content

Commit 0447eec

Browse files
fix(docs): clarified usage of validation with fine grained responses (aws-powertools#4101)
Co-authored-by: Leandro Damascena <[email protected]>
1 parent adfdb1f commit 0447eec

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Diff for: docs/core/event_handler/api_gateway.md

+7
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,13 @@ You can use the `Response` class to have full control over the response. For exa
874874
--8<-- "examples/event_handler_rest/src/fine_grained_responses_output.json"
875875
```
876876

877+
???- note "Using `Response` with data validation?"
878+
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.
879+
880+
```python hl_lines="8 26 32"
881+
--8<-- "examples/event_handler_rest/src/data_validation_fine_grained_response.py"
882+
```
883+
877884
### Compress
878885

879886
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.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from http import HTTPStatus
2+
from typing import Optional
3+
4+
import requests
5+
from pydantic import BaseModel, Field
6+
7+
from aws_lambda_powertools import Logger, Tracer
8+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response, content_types
9+
from aws_lambda_powertools.logging import correlation_paths
10+
from aws_lambda_powertools.utilities.typing import LambdaContext
11+
12+
tracer = Tracer()
13+
logger = Logger()
14+
app = APIGatewayRestResolver(enable_validation=True)
15+
16+
17+
class Todo(BaseModel):
18+
userId: int
19+
id_: Optional[int] = Field(alias="id", default=None)
20+
title: str
21+
completed: bool
22+
23+
24+
@app.get("/todos/<todo_id>")
25+
@tracer.capture_method
26+
def get_todo_by_id(todo_id: int) -> Response[Todo]:
27+
todo = requests.get(f"https://jsonplaceholder.typicode.com/todos/{todo_id}")
28+
todo.raise_for_status()
29+
return Response(
30+
status_code=HTTPStatus.OK.value,
31+
content_type=content_types.APPLICATION_JSON,
32+
body=todo.json(),
33+
)
34+
35+
36+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
37+
@tracer.capture_lambda_handler
38+
def lambda_handler(event: dict, context: LambdaContext) -> dict:
39+
return app.resolve(event, context)

0 commit comments

Comments
 (0)