### Cold Start Metric Output Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/metrics/datadog.md Example of the JSON output when a cold start metric is captured. ```json { "_aws": { "Timestamp": 1678886400000, "CloudWatchMetrics": [ { "Namespace": "ServerlessAirline", "Dimensions": [ ["service", "function_name"] ], "Metrics": [ { "Name": "ColdStart", "Unit": "Count" } ] } ] }, "service": "payment", "function_name": "my-lambda-function", "ColdStart": 1 } ``` -------------------------------- ### Run Cold Start Benchmark Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/benchmark/README.md Execute the benchmark script to compare Lambda cold-start times. Ensure the SAM CLI is installed and an S3 bucket is configured for deployment artifacts. ```bash export S3_BUCKET=code-artifact-s3-bucket cd benchmark ./benchmark.sh ``` -------------------------------- ### Getting All Enabled Features Configuration Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/feature_flags.md Example JSON configuration file defining features and their rules for the feature flags system. ```json { "version": "1", "defaultProvider": "AppConfig", "providers": { "AppConfig": { "sources": [ { "name": "feature-flags", "parameter": { "name": "feature-flags", "environment": "dev", "application": "my-app" } } ] } }, "features": { "new-checkout": { "rule": "ALWAYS_TRUE" }, "new-dashboard": { "rule": "ALWAYS_FALSE" } } } ``` -------------------------------- ### Install all extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install all core extras for Powertools. ```bash pip install "aws-lambda-powertools[all]" ``` -------------------------------- ### Install pre-release version with pip Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install pre-release versions from PyPi for early feedback. ```bash pip install --pre "aws-lambda-powertools" ``` -------------------------------- ### Shell script for basic CDK setup Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/build_recipes/build-tools.md Bash script to set up prerequisites for a basic AWS CDK project, including installing the AWS CDK CLI. ```bash --8<-- "examples/build_recipes/cdk/basic/setup-cdk.sh" ``` -------------------------------- ### ALB Handler Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/maintainers.md A sample handler for an Application Load Balancer using `ALBResolver`. It defines a GET endpoint for '/todos' that returns a simple 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) ``` -------------------------------- ### Capture Cold Start Metric Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/metrics/datadog.md Example of capturing cold start metrics using the `capture_cold_start_metric` parameter in the `log_metrics` decorator. ```python from aws_lambda_powertools import Metrics from aws_lambda_powertools.utilities.typing import LambdaContext metrics = Metrics(namespace="ServerlessAirline", service="payment") @metrics.log_metrics(namespace="ServerlessAirline", service="payment", capture_cold_start_metric=True) def lambda_handler(event: dict, context: LambdaContext): metrics.add_metric("booking_total", 100, "USD") return {"statusCode": 200} ``` -------------------------------- ### Install with pip Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Use pip to install the core aws-lambda-powertools package. ```bash pip install "aws-lambda-powertools" ``` -------------------------------- ### Getting Started with LambdaContext Typing Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/typing.md Demonstrates how to use the LambdaContext typing in your Lambda handler function for static type checking and IDE hints. ```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!" } ``` -------------------------------- ### Configure Idempotency Cache Persistence Layer Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/idempotency.md Quick start example for configuring the CachePersistenceLayer with basic settings. Ensure you have the necessary client library installed (e.g., valkey-glide or redis). ```python from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, Idempotency, CachePersistenceLayer @Idempotency(data_key_serializer="மையாக", config=IdempotencyConfig(expires_after_seconds=3600, max_age_seconds=600)) def lambda_handler(event, context): # Your Lambda function logic here return { "statusCode": 200, "body": "Hello from Lambda!" } # Example of initializing CachePersistenceLayer with default SSL # cache_layer = CachePersistenceLayer(host="localhost", port=6379) # Example of initializing CachePersistenceLayer with SSL disabled # cache_layer = CachePersistenceLayer(host="localhost", port=6379, ssl=False) # Example of initializing CachePersistenceLayer with custom table name # cache_layer = CachePersistenceLayer(table_name="my-idempotency-table", # host="localhost", # port=6379) # Example of initializing CachePersistenceLayer with custom attribute names # cache_layer = CachePersistenceLayer(table_name="my-idempotency-table", # host="localhost", # port=6379, # key_attr="my_key", # expiry_attr="my_expiry", # in_progress_expiry_attr="my_in_progress_expiry", # status_attr="my_status", # data_attr="my_data", # validation_key_attr="my_validation_key", # sort_key_attr="my_sort_key", # static_pk_value="my_static_pk_value") # Example of initializing CachePersistenceLayer with custom attribute names and SSL disabled # cache_layer = CachePersistenceLayer(table_name="my-idempotency-table", # host="localhost", # port=6379, # ssl=False, # key_attr="my_key", # expiry_attr="my_expiry", # in_progress_expiry_attr="my_in_progress_expiry", # status_attr="my_status", # data_attr="my_data", # validation_key_attr="my_validation_key", # sort_key_attr="my_sort_key", # static_pk_value="my_static_pk_value") ``` -------------------------------- ### Create Local Virtual Environment and Install Dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/contributing/setup.md Use the 'make dev' command to create a local virtual environment and install all necessary dependencies for development. ```bash make dev ``` -------------------------------- ### Async Support - Getting Started Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md Use `resolve_async()` and `async def` route handlers to support native async operations like non-blocking I/O. Sync and async handlers can coexist. ```python import asyncio from typing import Annotated from aws_lambda_powertools.utilities.typing import LambdaContext from aws_lambda_powertools.event_handler.api_gateway import APIGatewayProxyEvent, Response, Depends, Request from aws_lambda_powertools.event_handler import resolve_async def get_user_id(event: APIGatewayProxyEvent) -> str: return event.get("requestContext", {}).get("authorizer", {}).get("claims", {}).get("sub", "unknown") async def lambda_handler_async(event: APIGatewayProxyEvent, context: LambdaContext): user_id = get_user_id(event=event) # type: ignore await asyncio.sleep(0.1) # Simulate async I/O return Response( statusCode=200, content_type="application/json", body=f"{{'message': 'Hello {{user_id}}!'}}", ) def lambda_handler(event: APIGatewayProxyEvent, context: LambdaContext): # Use resolve_async to handle both sync and async handlers return resolve_async(lambda_handler_async, event, context) ``` -------------------------------- ### Install Kafka Consumer with Protobuf support Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/kafka.md Install the aws-lambda-powertools package with the 'kafka-consumer-protobuf' extra to enable Protocol Buffers message deserialization. ```bash pip install 'aws-lambda-powertools[kafka-consumer-protobuf]' ``` -------------------------------- ### Modulo Range Experimentation Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/feature_flags.md Demonstrates how to use modulo range segmentation for running experiments on a subset of users. The condition evaluates `START <= CONTEXT_VALUE % BASE <= END`. ```python from aws_lambda_powertools.utilities.feature_flags import FeatureFlags, Schema from aws_lambda_powertools.utilities.typing import LambdaContext feature_flags = FeatureFlags(schema=Schema.from_file("examples/feature_flags/src/modulo_range_features.json")) def lambda_handler(event: dict, context: LambdaContext): # Example of how to get a feature flag that is enabled based on modulo range is_new_checkout_enabled = feature_flags.evaluate(name="new-checkout", context=event) return { "statusCode": 200, "body": { "new_checkout_enabled": is_new_checkout_enabled } } ``` -------------------------------- ### Install AWS SDK for local development Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the AWS SDK as a dev dependency for local development. ```bash pip install "aws-lambda-powertools[aws-sdk]" ``` -------------------------------- ### Install uvicorn Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/includes/_http_resolver_local.md Install the uvicorn ASGI server using pip. This is required for local development with HttpResolverLocal. ```bash pip install uvicorn ``` -------------------------------- ### Example Wheel Breakdown: pydantic Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/build_recipes/cross-platform.md This example provides a detailed breakdown of a specific pydantic wheel filename, showing package name, version, Python/ABI tags, and platform tag. ```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 ``` -------------------------------- ### VPC Lattice v2 Resolver Setup Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md Demonstrates the setup for `VPCLatticeV2Resolver` when integrating with VPC Lattice using the recommended v2 payload format. ```python from aws_lambda_powertools.event_handler.vpc_lattice import VPCLatticeV2Resolver resolver = VPCLatticeV2Resolver() @resolver.get("/users") def get_users(): return {"message": "List of users"} def lambda_handler(event: dict, context: dict): return resolver.resolve(event, context) ``` -------------------------------- ### Middleware Early Return Output Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md Example JSON output demonstrating the effect of an early return in middleware processing. ```json { "message": "Hello World" } ``` -------------------------------- ### VPC Lattice v1 Resolver Setup Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md Shows the setup for `VPCLatticeResolver` when integrating with VPC Lattice using the v1 payload format. ```python from aws_lambda_powertools.event_handler.vpc_lattice import VPCLatticeResolver resolver = VPCLatticeResolver() @resolver.get("/products") def get_products(): return {"message": "List of products"} def lambda_handler(event: dict, context: dict): return resolver.resolve(event, context) ``` -------------------------------- ### Install Kafka Consumer with Avro support Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/kafka.md Install the aws-lambda-powertools package with the 'kafka-consumer-avro' extra to enable Avro message deserialization. ```bash pip install 'aws-lambda-powertools[kafka-consumer-avro]' ``` -------------------------------- ### Install Kafka Consumer with JSON support Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/kafka.md Install the aws-lambda-powertools package with the base dependencies to support JSON deserialization for Kafka messages. ```bash pip install aws-lambda-powertools ``` -------------------------------- ### Python Wheel Naming Convention Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/build_recipes/cross-platform.md This example breaks down the components of a Python wheel filename, illustrating how platform compatibility is encoded. ```txt {package}-{version}-{python tag}-{abi tag}-{platform tag}.whl ``` -------------------------------- ### AWS Serverless Application Model (SAM) example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/metrics.md This snippet shows an example of configuring AWS Serverless Application Model (SAM) for metrics. ```yaml AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: Sample SAM Template Parameters: # More info about Parameters in AWS Serverless Application Model # https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-template-parameters.html HelloWorldFunctionIamRole: Type: String Default: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" Description: "Existing IAM role to assign to the Lambda function." Globals: Function: Timeout: 3 MemorySize: 128 Runtime: python3.9 Architectures: - x86_64 Environment: Variables: POWERTOOLS_SERVICE_NAME: "ServerlessAirline" POWERTOOLS_METRICS_NAMESPACE: "ServerlessAirline" LOG_LEVEL: "INFO" Api: Cors: AllowMethods: "GET,POST,PUT,DELETE,OPTIONS" AllowHeaders: "*" AllowOrigin: "*" Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.lambda_handler Policies: - AWSLambdaBasicExecutionRole Events: HelloWorld: Type: Api Properties: Path: /hello Method: get Outputs: # Serverless REST API HelloWorldAPI: Description: "API Gateway endpoint URL for Prod stage for Hello World function" Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" HelloWorldFunction: Description: "Hello World Lambda Function ARN" Value: !GetAtt HelloWorldFunction.Arn HelloWorldFunctionIamRole: Description: "Implicit IAM Role created for Hello World function" Value: !GetAtt HelloWorldFunctionRole.Arn ``` -------------------------------- ### Lambda Function URL Resolver Setup Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md Illustrates the setup for `LambdaFunctionUrlResolver` when using AWS Lambda Function URLs. It shows the basic structure for defining a handler. ```python from aws_lambda_powertools.event_handler.lambda_function_url import LambdaFunctionUrlResolver resolver = LambdaFunctionUrlResolver() @resolver.get("/items/{item_id}") def get_item(item_id): return {"message": f"Details for item {item_id}"} def lambda_handler(event: dict, context: dict): return resolver.resolve(event, context) ``` -------------------------------- ### Initialize Sample Project with SAM CLI Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/tutorial/index.md Use SAM CLI to initialize a new serverless project with a Python runtime and pip dependency manager. ```bash sam init --runtime python3.14 --dependency-manager pip --app-template hello-world --name powertools-quickstart ``` -------------------------------- ### All Providers with Custom Boto3 Client Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/parameters.md Demonstrates how to instantiate all built-in providers with custom low-level and high-level boto3 clients. ```python from aws_lambda_powertools import Parameters # SSMProvider expects a low-level client ssm_client = boto3.client("ssm") ssm_provider = Parameters(boto3_client=ssm_client) # SecretsProvider expects a low-level client secrets_client = boto3.client("secretsmanager") secrets_provider = Parameters(boto3_client=secrets_client) # AppConfigProvider expects a low-level client appconfig_client = boto3.client("appconfigdata") appconfig_provider = Parameters(boto3_client=appconfig_client) # DynamoDBProvider expects a high-level resource dynamodb_resource = boto3.resource("dynamodb") dynamodb_provider = Parameters(boto3_client=dynamodb_resource) ``` -------------------------------- ### Install pre-release version with uv Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Use uv to add pre-release versions to your project. ```bash uv add --prerelease allow "aws-lambda-powertools" ``` -------------------------------- ### Getting All Enabled Features Payload Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/feature_flags.md Example JSON payload representing the event data used when retrieving all enabled features. ```json { "requestId": "12345", "featureContext": { "user": { "id": "user-123", "email": "user@example.com" } } } ``` -------------------------------- ### Install pre-release version with poetry Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Add pre-release versions to your project using poetry. ```bash poetry add --allow-prereleases "aws-lambda-powertools" --group dev ``` -------------------------------- ### Example Application Code Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/parameters.md A sample application file demonstrating the usage of parameters, potentially with caching enabled. ```python from aws_lambda_powertools import Parameters # Instantiate the Parameters utility parameters = Parameters() def lambda_handler(event, context): # Retrieve a parameter, which will be cached on first call my_value = parameters.get_parameter("MY_PARAMETER_NAME") # Process the retrieved value return { "statusCode": 200, "body": f"Retrieved parameter value: {my_value}" } ``` -------------------------------- ### Install with uv Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Use uv to add the aws-lambda-powertools package. ```bash uv add "aws-lambda-powertools" ``` -------------------------------- ### Unit Test Feature Flags Locally Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/feature_flags.md Example of unit testing Feature Flags locally using pytest and pytest-mock. This demonstrates mocking the AppConfigStore response to verify rule evaluation without AWS setup. ```python from aws_lambda_powertools.utilities.feature_flags import FeatureFlags, SchemaValidationError def test_feature_flags_with_mocked_store(mock_app_config_store): # Mock the AppConfigStore response mock_app_config_store.get_configuration.return_value = { "version": 1, "features": { "new-checkout-experience": { "rule": "user.country = 'US'", "defaultServe": True } } } feature_flags = FeatureFlags() # Evaluate a feature flag with a mocked context is_enabled = feature_flags.evaluate(context={'country': 'US'}, name='new-checkout-experience') assert is_enabled is True is_enabled = feature_flags.evaluate(context={'country': 'CA'}, name='new-checkout-experience') assert is_enabled is False ``` -------------------------------- ### Run Local Documentation Website Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/contributing/setup.md Locally serve the documentation website to preview changes. This command is useful for contributors who want to see their documentation updates in real-time. ```bash make docs-local ``` -------------------------------- ### CDK Application Entry Point Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/build_recipes/build-tools.md Sets up the CDK application and defines the deployment environment. ```python from aws_cdk import App, Environment from powertools_cdk_stack import PowertoolsCdkStack app = App() # Define environment configuration # You can define multiple environments (dev, staging, prod) here # and pass them to the stack constructor. # Example for a single environment PowertoolsCdkStack( app, "PowertoolsCdkStack", env=Environment( account= "123456789012", # Replace with your AWS Account ID region= "us-east-1", # Replace with your AWS Region ), ) app.synth() ``` -------------------------------- ### Install Parser Utility Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/parser.md Install the Parser utility with Pydantic v2 support using pip. This is not necessary if installing via Lambda Layer/SAR. ```bash pip install aws-lambda-powertools[parser] ``` -------------------------------- ### AppSync Schema Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/appsync.md Example GraphQL schema definition for AppSync. ```typescript --8<-- "examples/event_handler_graphql/src/getting_started_schema.graphql" ``` -------------------------------- ### Initialize AppConfig Provider Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/parameters.md Example of initializing the AppConfig provider to retrieve configuration parameters. This snippet shows the necessary imports and provider instantiation. ```python from aws_lambda_powertools.utilities.parameters import AppConfigProvider # Initialize provider appconfig_provider = AppConfigProvider(application="my-app", environment="dev", configuration_profile="my-config") # Get parameter my_parameter = appconfig_provider.get("my-parameter") print(my_parameter) ``` -------------------------------- ### Install Valkey extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Valkey feature which requires valkey-glide. ```bash pip install "aws-lambda-powertools[valkey]" ``` -------------------------------- ### Set up Real Redis Client for Integration Testing Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/idempotency.md For integration testing with a real Redis instance, configure a Redis client and use it with the IdempotencyService. This example shows how to connect to a Redis instance, potentially running in Docker. ```python import redis from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, IdempotencyService def test_with_real_redis(): # Configure and connect to a real Redis client # Assumes Redis is running on localhost:6379 or specified host/port real_redis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) # Initialize IdempotencyService with the real Redis client idempotency_service = IdempotencyService(config=IdempotencyConfig(client=real_redis_client)) # Your test logic using the configured idempotency_service # ... # Example assertion (replace with your actual test) assert real_redis_client.ping() ``` -------------------------------- ### Sample project layout for monolithic function Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md Illustrates a project structure for a monolithic Lambda function with routes split into different files, demonstrating how to organize code for maintainability. ```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 ``` -------------------------------- ### Install Redis extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Redis feature which requires redis. ```bash pip install "aws-lambda-powertools[redis]" ``` -------------------------------- ### Application Load Balancer (ALB) Resolver Setup Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md Shows how to configure the `ALBResolver` for handling requests from an Application Load Balancer. This includes defining routes and associating them with handler functions. ```python from aws_lambda_powertools.event_handler.alb import ALBResolver resolver = ALBResolver() @resolver.get("/todos") def get_todos(): return {"message": "List of todos"} def lambda_handler(event: dict, context: dict): return resolver.resolve(event, context) ``` -------------------------------- ### Install Parser extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Parser feature which requires pydantic. ```bash pip install "aws-lambda-powertools[parser]" ``` -------------------------------- ### Install Validation extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Validation feature which requires fastjsonschema. ```bash pip install "aws-lambda-powertools[validation]" ``` -------------------------------- ### Create Logger Instance Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/logger.md Initialize a Logger instance with a service name. This is the recommended way to start using the logger. ```python from aws_lambda_powertools import Logger logger = Logger(service="my_service") ``` -------------------------------- ### Install Tracer extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Tracer feature which requires the aws-xray-sdk. ```bash pip install "aws-lambda-powertools[tracer]" ``` -------------------------------- ### Middleware with Parameters Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/middleware_factory.md Example of creating a middleware that accepts custom keyword arguments. This allows for more configurable middleware behavior. ```python from aws_lambda_powertools.utilities.middleware_factory import lambda_handler_decorator def custom_middleware(handler, event, context, custom_param): print(f"Executing custom middleware with param: {custom_param}") return handler(event, context) @lambda_handler_decorator(custom_param="my_value") def lambda_handler(event, context): print("Executing Lambda handler") return { "statusCode": 200, "body": "Handler executed" } ``` -------------------------------- ### Datadog Metrics Output Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/metrics/datadog.md Example of the JSON output when Datadog metrics are logged. ```json { "_aws": { "Timestamp": 1678886400000, "CloudWatchMetrics": [ { "Namespace": "ServerlessAirline", "Dimensions": [ ["service", "status"] ], "Metrics": [ { "Name": "booking_processed", "Unit": "Count" }, { "Name": "booking_failed", "Unit": "Count" } ] } ] }, "service": "payment", "booking_total": 100, "booking_processed": 1, "booking_failed": 1, "status": "processed" } ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/tests/performance/data_masking/load_test_data_masking/pt-load-test-stack/README.md Install the necessary Python dependencies for running tests using pip. ```bash pt-load-test-stack$ pip install -r tests/requirements.txt --user ``` -------------------------------- ### Install Kafka (Protobuf) extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Kafka (Protobuf) feature which requires protobuf. ```bash pip install "aws-lambda-powertools[kafka-consumer-protobuf]" ``` -------------------------------- ### Install Kafka (Avro) extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Kafka (Avro) feature which requires avro. ```bash pip install "aws-lambda-powertools[kafka-consumer-avro]" ``` -------------------------------- ### Run Local Documentation Website with Docker Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/contributing/setup.md If you prefer using Docker, this command will build and run the documentation website locally within a Docker container. ```bash make docs-local-docker ``` -------------------------------- ### Install Datadog Metrics extra dependencies Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/getting-started/install.md Install the Datadog Metrics feature which requires datadog-lambda. ```bash pip install "aws-lambda-powertools[datadog]" ``` -------------------------------- ### JSON: Example Response Payload Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/core/event_handler/api_gateway.md An example JSON response payload after successful validation and processing. ```json { "id": "123" } ``` -------------------------------- ### uv setup with pyproject.toml Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/build_recipes/build-tools.md Configures project dependencies using uv and pyproject.toml. This is uv's recommended approach for managing Python projects. ```toml [tool.uv.dependencies] aws-lambda-powertools = { version = "3.18.0", extras = ["all"] } pydantic = "2.10.4" requests = ">=3.18.0" [tool.uv.dev-dependencies] pytest = "*" ``` -------------------------------- ### Optimize Lambda Cold Starts Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/build_recipes/troubleshooting.md Implement this solution to reduce high initialization durations and prevent timeouts on the first invocation of your Lambda function. ```bash --8<-- "examples/build_recipes/troubleshooting/optimize-cold-starts.sh" ``` -------------------------------- ### AppConfig Provider Payload Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/feature_flags.md Example JSON payload structure for AWS AppConfig configuration. ```json { "feature_flags": { "data": { "feature_x": true, "another_feature": false } } } ``` -------------------------------- ### Initialize SAM Application with Powertools Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/index.md Initializes a new AWS SAM application with Python runtime and includes Powertools for AWS Lambda. ```bash sam init --app-template hello-world-powertools-python --name sam-app --package-type Zip --runtime python3.13 --no-tracing ``` -------------------------------- ### Erase Data Output Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/data_masking.md An example JSON output after applying data erasure operations. ```json --8<-- "examples/data_masking/src/getting_started_erase_data_output.json" ``` -------------------------------- ### JSON: Features for Cache Adjustment Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/feature_flags.md Example JSON payload defining features, used in conjunction with cache adjustment examples. This payload is a placeholder and its content is less critical than the Python code demonstrating cache configuration. ```json { "features": { "new_dashboard": { "default": true } } } ``` -------------------------------- ### JSON: Payload for Cache Adjustment Example Source: https://github.com/awslabs/aws-lambda-powertools-python/blob/develop/docs/utilities/feature_flags.md Example JSON payload for feature flags, used in conjunction with cache adjustment examples. This payload is a placeholder and its content is less critical than the Python code demonstrating cache configuration. ```json { "new_dashboard": { "default": true } } ```