diff --git a/docs/core/event_handler/api_gateway.md b/docs/core/event_handler/api_gateway.md index 87263062f4f..a87eefbd5cd 100644 --- a/docs/core/event_handler/api_gateway.md +++ b/docs/core/event_handler/api_gateway.md @@ -357,7 +357,7 @@ You can access the raw payload via `body` property, or if it's a JSON string you #### Headers -Similarly to [Query strings](#query-strings), you can access headers as dictionary via `app.current_event.headers`, or by name via `get_header_value`. +Similarly to [Query strings](#query-strings-and-payload), you can access headers as dictionary via `app.current_event.headers`, or by name via `get_header_value`. === "app.py" @@ -377,6 +377,66 @@ Similarly to [Query strings](#query-strings), you can access headers as dictiona return app.resolve(event, context) ``` +### Raising HTTP errors + +You can easily raise any HTTP Error back to the client using `ServiceError` exception. + +!!! info "If you need to send custom headers, use [Response](#fine-grained-responses) class instead." + +Additionally, we provide pre-defined errors for the most popular ones such as HTTP 400, 401, 404, 500. + + +=== "app.py" + + ```python hl_lines="4-10 20 25 30 35 39" + from aws_lambda_powertools import Logger, Tracer + from aws_lambda_powertools.logging import correlation_paths + from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver + from aws_lambda_powertools.event_handler.exceptions import ( + BadRequestError, + InternalServerError, + NotFoundError, + ServiceError, + UnauthorizedError, + ) + + tracer = Tracer() + logger = Logger() + + app = ApiGatewayResolver() + + @app.get(rule="/bad-request-error") + def bad_request_error(): + # HTTP 400 + raise BadRequestError("Missing required parameter") + + @app.get(rule="/unauthorized-error") + def unauthorized_error(): + # HTTP 401 + raise UnauthorizedError("Unauthorized") + + @app.get(rule="/not-found-error") + def not_found_error(): + # HTTP 404 + raise NotFoundError + + @app.get(rule="/internal-server-error") + def internal_server_error(): + # HTTP 500 + raise InternalServerError("Internal server error") + + @app.get(rule="/service-error", cors=True) + def service_error(): + raise ServiceError(502, "Something went wrong!") + # alternatively + # from http import HTTPStatus + # raise ServiceError(HTTPStatus.BAD_GATEWAY.value, "Something went wrong) + + def handler(event, context): + return app.resolve(event, context) + ``` + + ## Advanced ### CORS @@ -401,7 +461,7 @@ This will ensure that CORS headers are always returned as part of the response w @app.get("/hello/") @tracer.capture_method def get_hello_you(name): - return {"message": f"hello {name}}"} + return {"message": f"hello {name}"} @app.get("/hello", cors=False) # optionally exclude CORS from response, if needed @tracer.capture_method @@ -647,6 +707,30 @@ Like `compress` feature, the client must send the `Accept` header with the corre } ``` +### Debug mode + +You can enable debug mode via `debug` param, or via `POWERTOOLS_EVENT_HANDLER_DEBUG` [environment variable](../../index.md#environment-variables). + +This will enable full tracebacks errors in the response, print request and responses, and set CORS in development mode. + +!!! warning "This might reveal sensitive information in your logs and relax CORS restrictions, use it sparingly." + +=== "debug.py" + + ```python hl_lines="3" + from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver + + app = ApiGatewayResolver(debug=True) + + @app.get("/hello") + def get_hello_universe(): + return {"message": "hello universe"} + + def lambda_handler(event, context): + return app.resolve(event, context) + ``` + + ## Testing your code You can test your routes by passing a proxy event request where `path` and `httpMethod`. diff --git a/docs/index.md b/docs/index.md index ce0573915fd..104ed1d85d6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -229,6 +229,7 @@ aws serverlessrepo list-application-versions \ | **POWERTOOLS_LOGGER_LOG_EVENT** | Logs incoming event | [Logging](./core/logger) | `false` | | **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logging](./core/logger) | `0` | | **POWERTOOLS_LOG_DEDUPLICATION_DISABLED** | Disables log deduplication filter protection to use Pytest Live Log feature | [Logging](./core/logger) | `false` | +| **POWERTOOLS_EVENT_HANDLER_DEBUG** | Enables debugging mode for event handler | [Event Handler](./core/event_handler/api_gateway.md#debug-mode) | `false` | | **LOG_LEVEL** | Sets logging level | [Logging](./core/logger) | `INFO` | ## Debug mode