### Install all extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with all core extra dependencies. ```bash pip install "aws-lambda-powertools[all]" ``` -------------------------------- ### Install with pip Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Use pip to install the AWS Lambda Powertools library. ```bash pip install "aws-lambda-powertools" ``` -------------------------------- ### Install Kafka Consumer with Protobuf support Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/kafka.md Install the aws-lambda-powertools package with the kafka-consumer-protobuf extra for Protocol Buffers deserialization. ```bash pip install 'aws-lambda-powertools[kafka-consumer-protobuf]' ``` -------------------------------- ### Middleware Early Return Output Example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md Example JSON output demonstrating an early return scenario. ```json { "statusCode": 200, "body": "Short-circuited" } ``` -------------------------------- ### Example Application Code Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/parameters.md This snippet shows an example application structure that might utilize the Parameters Utility. ```python from aws_lambda_powertools import Logger, Metrics, Tracer from aws_lambda_powertools.utilities.parameters import get_parameter, ParameterDataType from aws_lambda_powertools.utilities.typing import LambdaContext logger = Logger() tracer = Tracer() metrics = Metrics(namespace="PowertoolsExamples", service="Parameters") @tracer.capture_lambda_handler def lambda_handler(event: dict, context: LambdaContext): logger.info("Parameters utility example") # Example of getting a parameter parameter = get_parameter("my_parameter", data_type=ParameterDataType.STRING) logger.info(f"Parameter value: {parameter}") metrics.add_metric("SuccessfulParameterRetrieval", 1, "count") return { "parameter_value": parameter, } ``` -------------------------------- ### Install Kafka Consumer with Avro support Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/kafka.md Install the aws-lambda-powertools package with the kafka-consumer-avro extra for Avro deserialization. ```bash pip install 'aws-lambda-powertools[kafka-consumer-avro]' ``` -------------------------------- ### Async Support: Getting Started Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md Use `resolve_async()` to natively support async route handlers with `async/await`. Define your route handler as `async def` and use `asyncio.run()` to execute. ```python import asyncio from typing import Annotated from aws_lambda_powertools.utilities.typing import LambdaContext from aws_lambda_powertools.event_handler.api_gateway import APIGatewayRestResolver from aws_lambda_powertools.utilities.data_classes.api_gateway import APIGatewayProxyEvent from aws_lambda_powertools.utilities.dependency_injector.decorators import Depends app = APIGatewayRestResolver() def get_data_sync() -> str: return "sync_data" async def get_data_async() -> str: await asyncio.sleep(1) return "async_data" @app.get("/sync") def get_sync_data(data: Annotated[str, Depends(get_data_sync)]) -> dict: return {"data": data} @app.get("/async") async def get_async_data(data: Annotated[str, Depends(get_data_async)]) -> dict: return {"data": data} def lambda_handler(event: APIGatewayProxyEvent, context: LambdaContext): return app.resolve_async(event, context) ``` -------------------------------- ### CDK Project Setup Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/build_recipes/build-tools.md Prerequisites and initialization commands for AWS CDK projects. ```bash --8<-- "examples/build_recipes/cdk/basic/setup-cdk.sh" ``` -------------------------------- ### Create ALB Resolver and Define GET Endpoint Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/maintainers.md Instantiate ALBResolver from aws_lambda_powertools.event_handler and define HTTP GET endpoints using decorators. This example sets up a '/todos' endpoint that returns a basic JSON response. ```python from aws_lambda_powertools.event_handler import ALBResolver, Response, content_types app = ALBResolver() @app.get("/todos") def hello(): return Response( status_code=200, content_type=content_types.TEXT_PLAIN, body="Hello world", cookies=["CookieMonster", "MonsterCookie"], headers={"Foo": ["bar", "zbr"]}, ) def lambda_handler(event, context): return app.resolve(event, context) ``` -------------------------------- ### Install Kafka Consumer with JSON support Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/kafka.md Install the aws-lambda-powertools package with the JSON extra for Kafka consumer functionality. ```bash pip install aws-lambda-powertools ``` -------------------------------- ### Install with uv Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Use uv to add the AWS Lambda Powertools library to your project. ```bash uv add "aws-lambda-powertools" ``` -------------------------------- ### Setup Development Environment Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/CONTRIBUTING.md Run this command within your local virtual environment to set up the development environment for the project. ```bash make dev ``` -------------------------------- ### Install uvicorn Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/includes/_http_resolver_local.md Install the uvicorn ASGI server using pip. This is required to run the HttpResolverLocal for local development. ```bash pip install uvicorn ``` -------------------------------- ### Install pre-release versions with pip Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install pre-release versions of AWS Lambda Powertools using pip for early feedback. ```bash pip install --pre "aws-lambda-powertools" ``` -------------------------------- ### Install AWS SDK for local development Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS SDK as a dev dependency for local development with AWS Lambda Powertools. ```bash pip install "aws-lambda-powertools[aws-sdk]" ``` -------------------------------- ### Optimize cold start performance Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/build_recipes/troubleshooting.md Address high initialization duration and timeouts by optimizing function startup behavior. ```bash --8<-- "examples/build_recipes/troubleshooting/optimize-cold-starts.sh" ``` -------------------------------- ### AppConfigProvider Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/parameters.md Provides an example of initializing and using the AppConfigProvider. ```APIDOC ## AppConfigProvider ### Description Initializes and uses the AppConfigProvider to retrieve configuration from AWS AppConfig. ### Method `AppConfigProvider(application: str, environment: str, profile: str)` ### Endpoint N/A (This is a client-side provider) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from aws_lambda_powertools.utilities.parameters import AppConfigProvider appconfig_provider = AppConfigProvider( application="my-app", environment="dev", profile="my-profile" ) config = appconfig_provider.get_configuration() ``` ### Response #### Success Response (200) - **configuration** (dict) - The retrieved configuration from AWS AppConfig. #### Response Example ```json { "some_key": "some_value" } ``` ``` -------------------------------- ### Start Local API Server Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/tests/performance/data_masking/load_test_data_masking/pt-load-test-stack/README.md Starts a local server that emulates your application's API Gateway. This allows you to test API endpoints before deploying to AWS. ```bash pt-load-test-stack$ sam local start-api ``` -------------------------------- ### Install Tracer extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with tracer dependencies, which includes aws-xray-sdk. ```bash pip install "aws-lambda-powertools[tracer]" ``` -------------------------------- ### Install Kafka (Protobuf) extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with Kafka (Protobuf) dependencies, which includes protobuf. ```bash pip install "aws-lambda-powertools[kafka-consumer-protobuf]" ``` -------------------------------- ### DynamoDB IaC Examples for Idempotency Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/idempotency.md Infrastructure as Code examples for setting up DynamoDB for idempotency using SAM, CDK, and Terraform. ```yaml --8<-- "examples/idempotency/templates/sam.yaml" ``` ```python --8<-- "examples/idempotency/templates/cdk.py" ``` ```terraform --8<-- "examples/idempotency/templates/terraform.tf" ``` -------------------------------- ### Capture cold start metrics Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/metrics.md Enable cold start metric capture using the capture_cold_start_metric parameter in the log_metrics decorator. ```python --8<-- "examples/metrics/src/capture_cold_start_metric.py" ``` ```json --8<-- "examples/metrics/src/capture_cold_start_metric_output.json" ``` -------------------------------- ### Install pre-release versions with uv Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Add pre-release versions of AWS Lambda Powertools using uv, allowing pre-releases. ```bash uv add --prerelease allow "aws-lambda-powertools" ``` -------------------------------- ### Install with pdm Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Use pdm to add the AWS Lambda Powertools library to your project. ```bash pdm add "aws-lambda-powertools" ``` -------------------------------- ### AWS Serverless Application Model (SAM) example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/tracer.md Configure IAM permissions for AWS X-Ray in a SAM template. ```yaml --8<-- "examples/tracer/sam/template.yaml" ``` -------------------------------- ### Install with poetry Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Use poetry to add the AWS Lambda Powertools library to your project. ```bash poetry add "aws-lambda-powertools" ``` -------------------------------- ### Install Test Dependencies with PIP Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/tests/performance/data_masking/load_test_data_masking/pt-load-test-stack/README.md Install the necessary Python packages for running tests using pip. This command should be run from the project's root directory. ```bash pip install -r tests/requirements.txt --user ``` -------------------------------- ### Datadog cold start metric output Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/metrics/datadog.md This JSON output shows the `ColdStart` metric captured during a cold start invocation, along with application metrics. ```json { "namespace": "ServerlessAirline", "series": [ { "metric": "ServerlessAirline.Payment.ColdStart", "points": [ [1678886400, 1] ], "type": "count", "tags": [ "service:Payment", "function_name:my-lambda-function" ] }, { "metric": "ServerlessAirline.Payment.SuccessfulPayment", "points": [ [1678886400, 1] ], "type": "count", "tags": [ "service:Payment" ] } ] } ``` -------------------------------- ### SQS Event Model Example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/parser.md This example demonstrates how to use the SqsModel to parse an SQS event. The code highlights the import and usage of the SqsModel, along with a sample SQS event payload. ```APIDOC ## SQS Event Model Example ### Description This example demonstrates how to use the `SqsModel` to parse an SQS event. The code highlights the import and usage of the `SqsModel`, along with a sample SQS event payload. ### Request Example ```python from aws_lambda_powertools.utilities.parser import parse, BaseModel class SqsModel(BaseModel): """SQS event model""" id: str sender_id: str approximate_first_receive_timestamp: str def lambda_handler(event, context): # Parse SQS event sqs_event: SqsModel = parse(event=event, model=SqsModel) # Access event data print(f"Message ID: {sqs_event.id}") print(f"Sender ID: {sqs_event.sender_id}") print(f"Approximate First Receive Timestamp: {sqs_event.approximate_first_receive_timestamp}") ``` ### Sample Event ```json { "id": "19dd0b57-b218-4536-a07f-118073633324", "senderId": "123456789012", "approximateFirstReceiveTimestamp": "1523047710000" } ``` ``` -------------------------------- ### Global Middlewares Module Example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md Demonstrates that raising an exception or returning a Response object early will short-circuit the middleware chain. ```python from aws_lambda_powertools.utilities.typing import LambdaContext from aws_lambda_powertools.event_handler.api_gateway import APIGatewayProxyEvent, Response def middleware_one(event: APIGatewayProxyEvent, context: LambdaContext): print("Middleware One - Before") # Raising an exception OR returning a Response object early will short-circuit the middleware chain. return Response(status_code=200, body="Short-circuited") def middleware_two(event: APIGatewayProxyEvent, context: LambdaContext): print("Middleware Two - Before") return Response(status_code=200, body="Success") def lambda_handler(event: dict, context: LambdaContext): return APIGatewayProxyEvent(event=event, context=context).handle( middleware_one, middleware_two ) ``` -------------------------------- ### Inspect CDK Output Directory Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/maintainers.md Example directory structure of the cdk.out folder after synthesizing multiple features. ```shell total 8 drwxr-xr-x 18 lessa staff 576B Sep 6 15:38 event-handler drwxr-xr-x 3 lessa staff 96B Sep 6 15:08 layer_build -rw-r--r-- 1 lessa staff 32B Sep 6 15:08 layer_build.diff drwxr-xr-x 18 lessa staff 576B Sep 6 15:38 logger drwxr-xr-x 18 lessa staff 576B Sep 6 15:38 metrics drwxr-xr-x 22 lessa staff 704B Sep 9 10:52 tracer ``` -------------------------------- ### Getting Started with LambdaContext Typing Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/typing.md Use LambdaContext typing in your handler method for IDE type hints and static analysis. This example shows basic usage. ```python from aws_lambda_powertools.utilities.typing import LambdaContext def lambda_handler(event: dict, context: LambdaContext): print(f"Function name: {context.function_name}") return { "statusCode": 200, "body": "Hello from Lambda!" } ``` -------------------------------- ### Initialize Sample Project with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/tutorial/index.md Use SAM CLI to bootstrap a new Lambda project with Python runtime and pip dependency manager. ```bash sam init --runtime python3.14 --dependency-manager pip --app-template hello-world --name powertools-quickstart ``` -------------------------------- ### Basic HttpResolver Usage Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/includes/_http_resolver_local.md Demonstrates the basic setup for HttpResolverLocal. This code can be run with any ASGI server like uvicorn. ```python from aws_powertools.event_handler.api_gateway import HttpResolverLocal app = HttpResolverLocal() @app.get("/hello") def hello_world(): return {"message": "hello world"} ``` -------------------------------- ### Handling custom input types and serializers Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/data_masking.md Examples for processing various input types and configuring custom JSON serialization. ```python --8<-- "examples/data_masking/src/working_with_custom_types.py" ``` ```python --8<-- "examples/data_masking/src/working_with_pydantic_types.py" ``` ```python --8<-- "examples/data_masking/src/working_with_dataclass_types.py" ``` ```python --8<-- "examples/data_masking/src/advanced_custom_serializer.py" ``` -------------------------------- ### Run Local Documentation Website with Docker Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/CONTRIBUTING.md Build and serve the main documentation website locally using Docker. ```bash make docs-local-docker ``` -------------------------------- ### Invoke Lambda Function Locally via Curl Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/tutorial/index.md Example of using curl to send a GET request to the locally running API Gateway endpoint. ```bash curl http://127.0.0.1:3000/hello ``` -------------------------------- ### Run Local Documentation Website Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/CONTRIBUTING.md Build and serve the main documentation website locally. For Docker users, use 'make docs-local-docker'. ```bash make docs-local ``` -------------------------------- ### Customize API Operations Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/openapi.md Customize API operations by including extra parameters when defining your routes. This example adds 'operationId' and 'tags' to a GET request. ```python from aws_lambda_powertools.utilities.typing import LambdaContext from aws_lambda_powertools.event_handler.api_gateway import APIGatewayRestResolver app = APIGatewayRestResolver() @app.get("/", summary="Get the greeting message", description="Returns a greeting message.", operationId="getGreeting", tags=["Greetings"]) def get_greeting() -> dict: return {"message": "Hello World"} @app.get("/items/{item_id}", summary="Get an item by ID", description="Returns an item by its ID.", operationId="getItemById", tags=["Items"]) def get_item(item_id: int) -> dict: return {"item_id": item_id} def lambda_handler(event: dict, context: LambdaContext): return app.resolve(event, context) app.enable_swagger( "/swagger", title="My API", description="My API description", version="1.0.0" ) ``` -------------------------------- ### Run Local API Reference Documentation Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/CONTRIBUTING.md Use this command to build and serve the API reference documentation locally. ```bash make docs-api-local ``` -------------------------------- ### Terraform configuration for Lambda Layer Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Example Terraform configuration for using SSM Parameter Store to get the AWS Lambda Powertools Layer ARN for x86_64 architecture. ```terraform --8<-- "examples/homepage/install/x86_64/terraform.tf" ``` -------------------------------- ### Configure AppConfig Provider Options Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/feature_flags.md Demonstrates initializing the AppConfig provider with specific options for environment, application, and configuration name. ```python --8<-- "examples/feature_flags/src/appconfig_provider_options.py" ``` ```json --8<-- "examples/feature_flags/src/appconfig_provider_options_payload.json" ``` ```json --8<-- "examples/feature_flags/src/appconfig_provider_options_features.json" ``` -------------------------------- ### Specialized Router Types Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md Utilize specialized router classes for specific event types to gain IDE type hints when accessing the `current_event` property. This example demonstrates the setup for APIGatewayRouter, APIGatewayHttpRouter, ALBRouter, and LambdaFunctionUrlRouter. ```python from aws_lambda_powertools.event_handler.api_gateway import APIGatewayRestResolver, APIGatewayHttpResolver, ALBResolver, LambdaFunctionUrlResolver from aws_lambda_powertools.event_handler.api_gateway.routers import APIGatewayRouter, APIGatewayHttpRouter, ALBRouter, LambdaFunctionUrlRouter from aws_lambda_powertools.utilities.typing import APIGatewayProxyEvent, APIGatewayProxyEventV2, ALBEvent, LambdaFunctionUrlEvent # APIGatewayProxyEvent apigw_router = APIGatewayRouter() @apigw_router.get("/items") def get_items(): return {"message": "get_items"} apigw_resolver = APIGatewayRestResolver() apigw_resolver.include_router(apigw_router, prefix="/v1") # APIGatewayProxyEventV2 apigw_http_router = APIGatewayHttpRouter() @apigw_http_router.get("/items") def get_items_v2(): return {"message": "get_items_v2"} apigw_http_resolver = APIGatewayHttpResolver() apigw_http_resolver.include_router(apigw_http_router, prefix="/v2") # ALBEvent alb_router = ALBRouter() @alb_router.get("/alb") def get_alb(): return {"message": "get_alb"} alb_resolver = ALBResolver() alb_resolver.include_router(alb_router, prefix="/alb") # LambdaFunctionUrlEvent lf_router = LambdaFunctionUrlRouter() @lf_router.get("/lf") def get_lf(): return {"message": "get_lf"} lf_resolver = LambdaFunctionUrlResolver() lf_resolver.include_router(lf_router, prefix="/lf") def lambda_handler(event, context): # You would typically route to the correct resolver based on the event source # For demonstration purposes, we'll just show the setup. pass ``` -------------------------------- ### Install aws-lambda-powertools[parser] Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/parser.md Install the required dependencies for Pydantic v2 before using the Parser utility. This command installs the parser extra. ```bash pip install aws-lambda-powertools[parser] ``` -------------------------------- ### Implement Custom S3 Store Provider Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/feature_flags.md Examples demonstrating the implementation and usage of a custom S3-based store provider for feature flags. ```python --8<-- "examples/feature_flags/src/working_with_own_s3_store_provider.py" ``` ```python --8<-- "examples/feature_flags/src/custom_s3_store_provider.py" ``` -------------------------------- ### Install Valkey extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with Valkey dependencies, which includes valkey-glide. ```bash pip install "aws-lambda-powertools[valkey]" ``` -------------------------------- ### Install Redis extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with Redis dependencies, which includes redis. ```bash pip install "aws-lambda-powertools[redis]" ``` -------------------------------- ### Install Parser extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with parser dependencies, which includes pydantic. ```bash pip install "aws-lambda-powertools[parser]" ``` -------------------------------- ### Install Validation extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with validation dependencies, which includes fastjsonschema. ```bash pip install "aws-lambda-powertools[validation]" ``` -------------------------------- ### Bootstrap Project via SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/tutorial/index.md Directly bootstrap a project using SAM CLI with a specific application template and runtime. ```shell sam init --app-template hello-world-powertools-python --name sam-app --package-type Zip --runtime python3.14 --no-tracing ``` -------------------------------- ### Async Middleware Example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md Shows how to implement and use an asynchronous middleware. Async middlewares should be defined with `async def` and use `await next_middleware(app)`. ```python import asyncio from aws_lambda_powertools.utilities.typing import LambdaContext from aws_lambda_powertools.event_handler.api_gateway import APIGatewayHttpResolver app = APIGatewayHttpResolver() async def async_middleware(next_middleware): async def wrapper(request): print("Executing async middleware before") response = await next_middleware(request) print("Executing async middleware after") return response return wrapper @app.middleware(async_middleware) @app.get("/items") async def get_items(request): return {"message": "Hello from async middleware!"} def lambda_handler(event: dict, context: LambdaContext): return asyncio.run(app.resolve_async(event, context)) ``` -------------------------------- ### Build and Deploy Serverless Application Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/tests/performance/data_masking/load_test_data_masking/pt-load-test-stack/README.md Use these commands to build your application locally and deploy it to AWS. The `sam build` command prepares your code, and `sam deploy --guided` walks you through the deployment process. ```bash sam build --use-container sam deploy --guided ``` -------------------------------- ### Understand Python wheel naming conventions Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/build_recipes/cross-platform.md Breakdown of the standard Python wheel filename format and an example of a specific package wheel. ```txt {package}-{version}-{python tag}-{abi tag}-{platform tag}.whl ``` ```txt pydantic-2.5.0-cp311-cp311-linux_x86_64.whl │ │ │ │ └─ Platform: Linux x86_64 │ │ │ └─ ABI: CPython 3.11 │ │ └─ Python: CPython 3.11 │ └─ Version: 2.5.0 └─ Package: pydantic ``` -------------------------------- ### Basic Route Syntax in Python Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md Demonstrates basic route definitions using path parameters. Ensure function parameter names match route parameter names (e.g., `` in route matches `user_id` in function signature). ```python from aws_lambda_powertools.event_handler.api_gateway import APIGatewayRestResolver app = APIGatewayRestResolver() @app.get("/users/") def get_user(user_id: str): return {"message": f"Hello from {user_id}"} @app.get("/api//users") def get_users_by_version(version: str): return {"message": f"Hello from API version {version}"} ``` -------------------------------- ### Sample Project Layout Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md This is a sample project layout for a monolithic Lambda function with routes split into different files, demonstrating a common structure for organizing API endpoints. ```shell . ├── pyproject.toml # project app & dev dependencies; poetry, pipenv, etc. ├── poetry.lock ├── src │ ├── __init__.py │ ├── requirements.txt # sam build detect it automatically due to CodeUri: src. poetry export --format src/requirements.txt │ └── todos │ ├── __init__.py │ ├── main.py # this will be our todos Lambda fn; it could be split in folders if we want separate fns same code base │ └── routers # routers module │ ├── __init__.py │ ├── health.py # /health routes. from routers import todos; health.router │ └── todos.py # /todos routes. from .routers import todos; todos.router ├── template.yml # SAM. CodeUri: src, Handler: todos.main.lambda_handler └── tests ├── __init__.py ├── unit │ ├── __init__.py │ └── test_todos.py # unit tests for the todos router │ └── test_health.py # unit tests for the health router └── functional ├── __init__.py ├── conftest.py # pytest fixtures for the functional tests └── test_main.py # functional tests for the main lambda handler ``` -------------------------------- ### API Gateway Proxy Event Example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/data_classes.md Example JSON structure for an API Gateway proxy integration event. ```json { "resource": "/items/{id}", "path": "/items/123", "httpMethod": "GET", "requestContext": { "resourcePath": "/items/{id}", "httpMethod": "GET" }, "pathParameters": { "id": "123" }, "headers": { "Accept": "application/json" }, "body": null, "isBase64Encoded": false } ``` -------------------------------- ### uv setup pyproject.toml Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/build_recipes/build-tools.md Configuration file for uv, defining project metadata and dependencies. uv uses this for dependency resolution and management. ```toml --8<-- "examples/build_recipes/uv/pyproject.toml" ``` -------------------------------- ### Sync Middleware Example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md Demonstrates how to use a synchronous middleware with the async chain. Sync middlewares are executed in a background thread to avoid blocking the event loop. ```python from aws_lambda_powertools.utilities.typing import LambdaContext from aws_lambda_powertools.event_handler.api_gateway import APIGatewayHttpResolver app = APIGatewayHttpResolver() def sync_middleware(next_middleware): def wrapper(request): print("Executing sync middleware before") response = next_middleware(request) print("Executing sync middleware after") return response return wrapper @app.middleware(sync_middleware) @app.get("/items") def get_items(request): return {"message": "Hello from sync middleware!"} def lambda_handler(event: dict, context: LambdaContext): return app.resolve(event, context) ``` -------------------------------- ### Install Kafka (Avro) extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with Kafka (Avro) dependencies, which includes avro. ```bash pip install "aws-lambda-powertools[kafka-consumer-avro]" ``` -------------------------------- ### Install Datadog Metrics extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with Datadog metrics dependencies, which includes datadog-lambda. ```bash pip install "aws-lambda-powertools[datadog]" ``` -------------------------------- ### Example Request Payload for Validating Payloads Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md This is an example JSON request payload that would be validated against the `Todo` Pydantic model. ```json { "id": 1, "name": "Buy groceries", "description": "Milk, Eggs, Bread" } ``` -------------------------------- ### Run Cold Start Benchmark Script Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/benchmark/README.md Execute the benchmark script from the benchmark directory. Ensure the S3_BUCKET environment variable is set. This script deploys resources using SAM CLI, runs performance tests, analyzes logs, and cleans up. ```bash export S3_BUCKET=code-artifact-s3-bucket cd benchmark ./benchmark.sh ``` -------------------------------- ### Install Data Masking extra dependencies Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/getting-started/install.md Install the AWS Lambda Powertools with data masking dependencies, which includes aws-encryption-sdk and jsonpath-ng. ```bash pip install "aws-lambda-powertools[datamasking]" ``` -------------------------------- ### Define Kafka Schema and Payload Examples Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/kafka.md Examples of schema definitions and corresponding event payloads for JSON, Avro, and Protobuf formats. ```json --8<-- "examples/kafka/consumer/schemas/user.json" ``` ```json --8<-- "examples/kafka/consumer/events/kafka_event_json.json" ``` ```json --8<-- "examples/kafka/consumer/schemas/user.avsc" ``` ```json --8<-- "examples/kafka/consumer/events/kafka_event_avro.json" ``` ```protobuf --8<-- "examples/kafka/consumer/schemas/user.proto" ``` ```json --8<-- "examples/kafka/consumer/events/kafka_event_protobuf.json" ``` -------------------------------- ### Example Response Payload for Validating Payloads Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/event_handler/api_gateway.md This is an example JSON response payload, demonstrating the output after processing the request and returning a string ID. ```json { "id": "1" } ``` -------------------------------- ### Build Serverless Application Locally Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/tests/performance/data_masking/load_test_data_masking/pt-load-test-stack/README.md Builds the application and its dependencies, saving the deployment package in the `.aws-sam/build` folder. Ensure you have the necessary tools like Docker installed. ```bash pt-load-test-stack$ sam build --use-container ``` -------------------------------- ### Build and Deploy Serverless Application with SAM Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/tutorial/index.md Use AWS SAM CLI to build your Lambda function code and deploy your serverless application to AWS. The `--guided` flag prompts for necessary configuration details. ```bash > sam build && sam deploy --guided ... CloudFormation outputs from deployed stack ------------------------------------------------------------------------------------------------------------------------------------------ Outputs ------------------------------------------------------------------------------------------------------------------------------------------ Key HelloWorldFunctionIamRole Description Implicit IAM Role created for Hello World function Value arn:aws:iam::123456789012:role/sam-app-HelloWorldFunctionRole-1T2W3H9LZHGGV Key HelloWorldApi Description API Gateway endpoint URL for Prod stage for Hello World function Value https://1234567890.execute-api.eu-central-1.amazonaws.com/Prod/hello/ Key HelloWorldFunction Description Hello World Lambda Function ARN Value arn:aws:lambda:eu-central-1:123456789012:function:sam-app-HelloWorldFunction-dOcfAtYoEiGo ------------------------------------------------------------------------------------------------------------------------------------------ Successfully created/updated stack - sam-app in eu-central-1 ``` -------------------------------- ### Structured Log Output Example Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/tutorial/index.md Example of structured log output generated by AWS Powertools Logger, including service information, request details, and correlation ID. ```json { "level":"INFO", "location":"hello:17", "message":"Request from unknown received", "timestamp":"2021-10-22 16:29:58,367+0000", "service":"APP", "cold_start":true, "function_name":"HelloWorldFunction", "function_memory_size":"256", "function_arn":"arn:aws:lambda:us-east-1:123456789012:function:HelloWorldFunction", "function_request_id":"d50bb07a-7712-4b2d-9f5d-c837302221a2", "correlation_id":"bf9b584c-e5d9-4ad5-af3d-db953f2b10dc" } ``` -------------------------------- ### Build and Run API Gateway Locally Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/tutorial/index.md Command to build the SAM application and start a local API Gateway for testing. ```bash sam build && sam local start-api ``` -------------------------------- ### Capture cold start metric with Datadog Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/core/metrics/datadog.md Use the `capture_cold_start_metric` parameter in the `log_metrics` decorator to automatically capture cold start invocations as a separate Datadog metric named `ColdStart`. ```python from aws_lambda_powertools import Metrics from aws_lambda_powertools.utilities.typing import LambdaContext metrics = Metrics(namespace="ServerlessAirline", service="Payment", "datadog") @metrics.log_metrics(namespace="ServerlessAirline", service="Payment", capture_cold_start_metric=True) def lambda_handler(event: dict, context: LambdaContext): metrics.add_metric("SuccessfulPayment", 1, "count") return { "statusCode": 200, "body": "Payment successful" } ``` -------------------------------- ### Implement Custom Parameter Store Provider with Vault Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/utilities/parameters.md Example of creating a custom parameter store provider by inheriting from BaseProvider and implementing _get() and _get_multiple() for Hashicorp Vault. ```python from aws_lambda_powertools.utilities.parameters import BaseProvider class VaultProvider(BaseProvider): def __init__(self, vault_url: str, vault_token: str): self.vault_url = vault_url self.vault_token = vault_token super().__init__() def _get(self, key: str, decrypt: bool = True) -> str: # Implementation to retrieve a single parameter from Vault pass def _get_multiple(self, keys: list[str], decrypt: bool = True) -> dict[str, str]: # Implementation to retrieve multiple parameters from Vault pass # Example usage: # vault_provider = VaultProvider(vault_url="http://localhost:8200", vault_token="my-token") # parameter = vault_provider.get("my-key") ``` ```python from aws_lambda_powertools.utilities.parameters import BaseProvider class VaultProvider(BaseProvider): def __init__(self, vault_url: str, vault_token: str): self.vault_url = vault_url self.vault_token = vault_token super().__init__() def _get(self, key: str, decrypt: bool = True) -> str: # Implementation to retrieve a single parameter from Vault pass def _get_multiple(self, keys: list[str], decrypt: bool = True) -> dict[str, str]: # Implementation to retrieve multiple parameters from Vault pass # Example usage: # vault_provider = VaultProvider(vault_url="http://localhost:8200", vault_token="my-token") # parameter = vault_provider.get("my-key") ``` -------------------------------- ### Initialize SAM Application with Powertools Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/index.md Use the SAM CLI to initialize a new Python project with AWS Powertools for Lambda pre-configured. This command sets up a basic structure for a serverless application. ```bash sam init --app-template hello-world-powertools-python --name sam-app --package-type Zip --runtime python3.13 --no-tracing ``` -------------------------------- ### Build Linux Wheels Script Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/build_recipes/cross-platform.md This script forces the installation of Linux-compatible wheels using pip. It's useful when you need to ensure that only wheels built for Linux are installed, avoiding potential compilation issues. ```bash --8<-- "examples/build_recipes/build_multi_arch/build-linux-wheels.sh" ``` -------------------------------- ### Dockerfile for Poetry Lambda Builds Source: https://github.com/aws-powertools/powertools-lambda-python/blob/develop/docs/build_recipes/build-tools.md A Dockerfile to create a consistent build environment for Python Lambda functions using Poetry. It installs Poetry, copies project files, installs dependencies, and prepares the deployment package. ```dockerfile FROM python:3.9-slim-buster AS builder # Install Poetry RUN pip install poetry WORKDIR /app # Copy project files COPY pyproject.toml poetry.lock* ./ COPY src ./src # Install dependencies using Poetry RUN poetry install --no-root --no-interaction # Create deployment package RUN mkdir -p /lambda-package RUN cp -r /app/src/* /lambda-package/ RUN cp -r /app/.venv/lib/python3.9/site-packages/* /lambda-package/ # Package for Lambda RUN cd /lambda-package && zip -r /deployment.zip . FROM public.ecr.aws/lambda/python:3.9 COPY --from=builder /deployment.zip / RUN unzip /deployment.zip -d /opt/python # Set the CMD to your handler (e.g., app.lambda_handler) CMD [ "app.lambda_handler" ] ```