Skip to content

http resolver local

Http Resolver (ASGI)

HttpResolver is an ASGI-compatible resolver that lets you run your Powertools application with any ASGI server like uvicorn. It implements the ASGI specification, is lightweight with no external dependencies, and works seamlessly with Lambda or any environment that speaks HTTP.

If your Lambda is behind Lambda Web Adapter or any other HTTP proxy that speaks the HTTP protocol, it works seamlessly.

All existing resolver features work out of the box: routing, middleware, validation, OpenAPI/Swagger, CORS, exception handling, and more.

Install uvicorn:

1
pip install uvicorn
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from aws_lambda_powertools.event_handler import HttpResolver

app = HttpResolver()


@app.get("/hello/<name>")
def hello(name: str):
    return {"message": f"Hello, {name}!"}


# Lambda handler - same code works in Lambda
handler = app

Run locally: uvicorn app:app --reload

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from pydantic import BaseModel

from aws_lambda_powertools.event_handler import HttpResolver


class User(BaseModel):
    name: str
    age: int


app = HttpResolver(enable_validation=True)

app.enable_swagger(
    title="My API",
    version="1.0.0",
)


@app.post("/users")
def create_user(user: User) -> dict:
    return {"id": "123", "user": user.model_dump()}


handler = app

Access Swagger UI at http://localhost:8000/swagger

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from aws_lambda_powertools.event_handler import HttpResolver, Response

app = HttpResolver()


class NotFoundError(Exception):
    def __init__(self, resource: str):
        self.resource = resource


@app.exception_handler(NotFoundError)
def handle_not_found_error(exc: NotFoundError):
    return Response(
        status_code=404,
        content_type="application/json",
        body={"error": "Not Found", "resource": exc.resource},
    )


@app.not_found
def handle_not_found(exc: Exception):
    return Response(
        status_code=404,
        content_type="application/json",
        body={"error": "Route not found", "path": app.current_event.path},
    )


@app.get("/users/<user_id>")
def get_user(user_id: str):
    if user_id == "0":
        raise NotFoundError(f"User {user_id}")
    return {"user_id": user_id}


handler = app