Skip to content

docs(api-gateway): new HTTP service error exceptions #546

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 86 additions & 2 deletions docs/core/event_handler/api_gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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
Expand All @@ -401,7 +461,7 @@ This will ensure that CORS headers are always returned as part of the response w
@app.get("/hello/<name>")
@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
Expand Down Expand Up @@ -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`.
Expand Down
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down