Skip to content

Commit bf7e555

Browse files
docs: adding docs to Request object (#8105)
1 parent a26d64b commit bf7e555

File tree

4 files changed

+102
-15
lines changed

4 files changed

+102
-15
lines changed

docs/core/event_handler/api_gateway.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -943,6 +943,50 @@ Here's a sample middleware that extracts and injects correlation ID, using `APIG
943943
--8<-- "examples/event_handler_rest/src/middleware_getting_started_output.json"
944944
```
945945

946+
#### Accessing the Request object
947+
948+
After route resolution, Event Handler creates a `Request` object with the **resolved** route context. You can access it in two ways:
949+
950+
1. **`app.request`** - available in middleware functions.
951+
2. **`request: Request` type annotation** - injected automatically into route handlers as a parameter.
952+
953+
`Request` gives you the resolved route context that `app.current_event` doesn't have:
954+
955+
| Property | Example | Description |
956+
| --------------------- | ---------------------------------------- | ----------------------------------------------------- |
957+
| `route` | `/todos/{todo_id}` | Matched route pattern in OpenAPI path-template format |
958+
| `path_parameters` | `{"todo_id": "123"}` | Powertools-resolved path parameters |
959+
| `method` | `GET` | HTTP method (upper-case) |
960+
| `headers` | `{"content-type": "application/json"}` | Request headers |
961+
| `query_parameters` | `{"page": "1"}` | Query string parameters |
962+
| `body` | `'{"name": "task"}'` | Raw request body |
963+
| `json_body` | `{"name": "task"}` | Deserialized request body |
964+
965+
=== "Using `app.request` in middleware"
966+
967+
```python hl_lines="10 13-15 21" title="Accessing Request via app.request"
968+
--8<-- "examples/event_handler_rest/src/middleware_request_object.py"
969+
```
970+
971+
1. Access the resolved `Request` object from the app instance.
972+
2. `request.route` returns the matched route pattern, e.g. `/todos/{todo_id}`.
973+
3. `request.path_parameters` returns the Powertools-resolved parameters, e.g. `{"todo_id": "123"}`.
974+
4. You can include route metadata in the response headers.
975+
976+
=== "Using `request: Request` in route handlers"
977+
978+
```python hl_lines="7 10" title="Accessing Request via type annotation"
979+
--8<-- "examples/event_handler_rest/src/middleware_request_handler_injection.py"
980+
```
981+
982+
1. Add `request: Request` as a parameter - Event Handler injects it automatically.
983+
2. Access resolved route, path parameters, headers, query parameters, and body.
984+
985+
???+ note "When to use `Request` vs `app.current_event`"
986+
Use `Request` for **route-aware** logic like authorization, logging, and metrics - it gives you the matched route pattern and Powertools-resolved path parameters.
987+
988+
Use `app.current_event` when you need the **raw event** data like request context, stage variables, or authorizer context that is available from the start of the request, before route resolution.
989+
946990
#### Global middlewares
947991

948992
<figure markdown="span">
@@ -1112,7 +1156,7 @@ Keep the following in mind when authoring middlewares for Event Handler:
11121156
2. **Call the next middleware**. Return the result of `next_middleware(app)`, or a [Response object](#fine-grained-responses) when you want to [return early](#returning-early).
11131157
3. **Keep a lean scope**. Focus on a single task per middleware to ease composability and maintenance. In [debug mode](#debug-mode), we also print out the order middlewares will be triggered to ease operations.
11141158
4. **Catch your own exceptions**. Catch and handle known exceptions to your logic. Unless you want to raise [HTTP Errors](#raising-http-errors), or propagate specific exceptions to the client. To catch all and any exceptions, we recommend you use the [exception_handler](#exception-handling) decorator.
1115-
5. **Use context to share data**. Use `app.append_context` to [share contextual data](#sharing-contextual-data) between middlewares and route handlers, and `app.context.get(key)` to fetch them. We clear all contextual data at the end of every request.
1159+
5. **Use context to share data**. Use `app.append_context` to [share contextual data](#sharing-contextual-data) between middlewares and route handlers, and `app.context.get(key)` to fetch them. We clear all contextual data at the end of every request. For route-aware request data, use [`app.request`](#accessing-the-request-object) instead.
11161160

11171161
### Fine grained responses
11181162

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Request
2+
3+
app = APIGatewayRestResolver()
4+
5+
6+
@app.get("/todos/<todo_id>")
7+
def get_todo(todo_id: str, request: Request): # (1)!
8+
return {
9+
"id": todo_id,
10+
"route": request.route, # (2)!
11+
"user_agent": request.headers.get("user-agent", ""),
12+
}
13+
14+
15+
def lambda_handler(event, context):
16+
return app.resolve(event, context)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from aws_lambda_powertools import Logger
2+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response
3+
from aws_lambda_powertools.event_handler.middlewares import NextMiddleware
4+
5+
app = APIGatewayRestResolver()
6+
logger = Logger()
7+
8+
9+
def request_context_middleware(app: APIGatewayRestResolver, next_middleware: NextMiddleware) -> Response:
10+
request = app.request # (1)!
11+
12+
logger.append_keys(
13+
route=request.route, # (2)!
14+
method=request.method,
15+
path_parameters=request.path_parameters, # (3)!
16+
)
17+
18+
response = next_middleware(app)
19+
20+
response.headers["x-route-pattern"] = request.route # (4)!
21+
return response
22+
23+
24+
@app.get("/todos/<todo_id>", middlewares=[request_context_middleware])
25+
def get_todo(todo_id: str):
26+
return {"id": todo_id}
27+
28+
29+
def lambda_handler(event, context):
30+
return app.resolve(event, context)

poetry.lock

Lines changed: 11 additions & 14 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)