Skip to content

Commit e7e1103

Browse files
authored
docs(apigateway): add new not_found feature (#915)
1 parent b144f75 commit e7e1103

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

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

+87
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,93 @@ Similarly to [Query strings](#query-strings-and-payload), you can access headers
478478
return app.resolve(event, context)
479479
```
480480

481+
482+
### Handling not found routes
483+
484+
By default, we return `404` for any unmatched route.
485+
486+
You can use **`not_found`** decorator to override this behaviour, and return a custom **`Response`**.
487+
488+
=== "app.py"
489+
490+
```python hl_lines="11 13 16" title="Handling not found"
491+
from aws_lambda_powertools import Logger, Tracer
492+
from aws_lambda_powertools.logging import correlation_paths
493+
from aws_lambda_powertools.event_handler import content_types
494+
from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver, Response
495+
from aws_lambda_powertools.event_handler.exceptions import NotFoundError
496+
497+
tracer = Tracer()
498+
logger = Logger()
499+
app = ApiGatewayResolver()
500+
501+
@app.not_found
502+
@tracer.capture_method
503+
def handle_not_found_errors(exc: NotFoundError) -> Response:
504+
# Return 418 upon 404 errors
505+
logger.info(f"Not found route: {app.current_event.path}")
506+
return Response(
507+
status_code=418,
508+
content_type=content_types.TEXT_PLAIN,
509+
body="I'm a teapot!"
510+
)
511+
512+
513+
@app.get("/catch/me/if/you/can")
514+
@tracer.capture_method
515+
def catch_me_if_you_can():
516+
return {"message": "oh hey"}
517+
518+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
519+
@tracer.capture_lambda_handler
520+
def lambda_handler(event, context):
521+
return app.resolve(event, context)
522+
```
523+
524+
525+
### Exception handling
526+
527+
You can use **`exception_handler`** decorator with any Python exception. This allows you to handle a common exception outside your route, for example validation errors.
528+
529+
=== "app.py"
530+
531+
```python hl_lines="10 15" title="Exception handling"
532+
from aws_lambda_powertools import Logger, Tracer
533+
from aws_lambda_powertools.logging import correlation_paths
534+
from aws_lambda_powertools.event_handler import content_types
535+
from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver, Response
536+
537+
tracer = Tracer()
538+
logger = Logger()
539+
app = ApiGatewayResolver()
540+
541+
@app.exception_handler(ValueError)
542+
def handle_value_error(ex: ValueError):
543+
metadata = {"path": app.current_event.path}
544+
logger.error(f"Malformed request: {ex}", extra=metadata)
545+
546+
return Response(
547+
status_code=400,
548+
content_type=content_types.TEXT_PLAIN,
549+
body="Invalid request",
550+
)
551+
552+
553+
@app.get("/hello")
554+
@tracer.capture_method
555+
def hello_name():
556+
name = app.current_event.get_query_string_value(name="name")
557+
if name is not None:
558+
raise ValueError("name query string must be present")
559+
return {"message": f"hello {name}"}
560+
561+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
562+
@tracer.capture_lambda_handler
563+
def lambda_handler(event, context):
564+
return app.resolve(event, context)
565+
```
566+
567+
481568
### Raising HTTP errors
482569

483570
You can easily raise any HTTP Error back to the client using `ServiceError` exception.

Diff for: mkdocs.yml

+1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ theme:
4949
- navigation.sections
5050
- navigation.expand
5151
- navigation.top
52+
- navigation.instant
5253
icon:
5354
repo: fontawesome/brands/github
5455
logo: media/aws-logo-light.svg

0 commit comments

Comments
 (0)