/powertools-lambda-python:building-lambda-functions-with-powertools-pythonfrom powertools-lambda-python
Builds AWS Lambda functions in Python using Powertools for AWS Lambda, covering structured logging, tracing, metrics, event handlers, idempotency, batch processing, parameters, validation, and parsing.
Ships in powertools-lambda-python. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Powertools for AWS Lambda (Python) is a toolkit of independent utilities for Lambda functions: Logger, Tracer, Metrics, Event Handler, Idempotency, Batch Processing, Parameters, Parser, Validation, Feature Flags, Data Masking, Circuit Breaker, Kafka, Streaming and others. Each utility is designed around the Lambda execution model and adds as little as possible to cold start.
aws_lambda_powertoolsDo not use it for non-Lambda web frameworks, or for the Powertools libraries of other languages (TypeScript, Java, .NET). Do not use it when working inside the aws-powertools/powertools-lambda-python repository: there you are changing the library, not using it, and AGENTS.md at the repository root has the rules that apply.
references/. Each file is the full documentation page with every example inlined; open it and look for the section you need instead of reading the whole file.uv run python -c "import aws_lambda_powertools; print(aws_lambda_powertools.__version__)". The references describe the latest release.aws-lambda-powertools package with the extra the utility needs ([tracer], [parser], [validation], [datamasking], [redis], [valkey], [jwt], [oauth2], [all]). See references/installation.md.from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.metrics import MetricUnit
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger() # service name from POWERTOOLS_SERVICE_NAME
tracer = Tracer() # needs the [tracer] extra or the layer, and Active tracing on the function
metrics = Metrics() # namespace from POWERTOOLS_METRICS_NAMESPACE
@tracer.capture_method
def collect_payment(charge_id: str) -> dict:
return {"charge_id": charge_id, "status": "collected"}
@logger.inject_lambda_context(log_event=True)
@tracer.capture_lambda_handler
@metrics.log_metrics(capture_cold_start_metric=True)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
logger.info("Collecting payment", extra={"charge_id": event["charge_id"]})
metrics.add_metric(name="SuccessfulPayments", unit=MetricUnit.Count, value=1)
return collect_payment(event["charge_id"])
Create the three objects once at module level and reuse them across invocations. Use logger.append_keys(...) for keys that must appear in every following log line, extra= for one line only. inject_lambda_context adds cold start, function name, memory, ARN and request id; add correlation_id_path=correlation_paths.API_GATEWAY_REST (or another path from aws_lambda_powertools.logging.correlation_paths) to pick up a correlation id from the event.
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.exceptions import NotFoundError
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext
tracer = Tracer()
logger = Logger()
app = APIGatewayRestResolver(enable_validation=True)
@app.get("/todos/<todo_id>")
@tracer.capture_method
def get_todo(todo_id: int) -> dict:
todo = find_todo(todo_id)
if todo is None:
raise NotFoundError(f"todo {todo_id} not found")
return todo
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context)
Pick the resolver that matches the trigger: APIGatewayRestResolver (REST API), APIGatewayHttpResolver (HTTP API), ALBResolver, LambdaFunctionUrlResolver, VPCLatticeV2Resolver, AppSyncResolver, AppSyncEventsResolver, BedrockAgentResolver. With enable_validation=True, type hints on path, query, header and body parameters are validated and a 422 is returned on failure; app.get_openapi_json_schema() and app.enable_swagger() come from the same annotations. Split large APIs with Router and app.include_router(router, prefix="/v1"). See references/event-handler-rest-http.md and references/event-handler-openapi.md.
import os
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
persistence_layer = DynamoDBPersistenceLayer(table_name=os.environ["IDEMPOTENCY_TABLE"])
config = IdempotencyConfig(event_key_jmespath="order_id", expires_after_seconds=3600)
@idempotent(persistence_store=persistence_layer, config=config)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return create_order(event)
The table needs a string partition key named id and TTL on expiration. Use event_key_jmespath so the key is the business identifier, not the whole event. For a function inside the handler use @idempotent_function(data_keyword_argument="order", ...). Create one persistence layer instance per decorated function; sharing one instance between two decorated functions mixes their records. Redis and Valkey are supported through CachePersistenceLayer. See references/idempotency.md.
from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType, process_partial_response
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
processor = BatchProcessor(event_type=EventType.SQS)
def record_handler(record: SQSRecord) -> None:
payload = record.json_body # record.body for plain strings
logger.info(payload)
@logger.inject_lambda_context
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context)
The event source mapping must have ReportBatchItemFailures enabled, otherwise the whole batch is retried. Use EventType.KinesisDataStreams or EventType.DynamoDBStreams for the other sources, SqsFifoPartialProcessor for FIFO queues, and AsyncBatchProcessor with async_process_partial_response for async record handlers. Raise from record_handler to mark a record as failed; do not catch and swallow. See references/batch-processing.md.
from aws_lambda_powertools.utilities import parameters
api_key = parameters.get_parameter("/payments/api-key", decrypt=True, max_age=300)
settings = parameters.get_parameter("/payments/settings", transform="json")
db_secret = parameters.get_secret("payments/db", transform="json")
Values are cached for max_age seconds (5 seconds by default) inside the execution environment; call these inside the handler, not at import time, unless the value never changes. get_parameters fetches a path recursively, get_parameters_by_name fetches a batch, get_app_config reads AppConfig. Use SSMProvider, SecretsProvider, AppConfigProvider or DynamoDBProvider when you need a custom client or region. See references/parameters.md.
from aws_lambda_powertools.utilities.data_classes import event_source, S3Event
from aws_lambda_powertools.utilities.typing import LambdaContext
@event_source(data_class=S3Event)
def lambda_handler(event: S3Event, context: LambdaContext) -> None:
for record in event.records:
print(record.s3.bucket.name, record.s3.get_object.key)
Event source data classes give typed, dict-backed access without a dependency. When you need validation of the payload, use the Parser with Pydantic: @event_parser(model=MyModel, envelope=envelopes.SqsEnvelope) validates each record body against MyModel. Both have a class or model for every common event source; see references/event-source-data-classes.md and references/parser.md.
These come from the project's architecture decision records.
aws_lambda_powertools utilities at module level, but import heavy optional libraries (Pydantic models, boto3 clients) where they are used, and create clients once at module level, never per invocation.boto3 and botocore; do not add them to the deployment package or the layer, and do not pin urllib3 yourself.[all] is for development.aws_lambda_powertools, aws_lambda_powertools.event_handler, aws_lambda_powertools.utilities.<utility> and the .exceptions/.types modules. Names starting with _ are internal and change without notice.POWERTOOLS_SERVICE_NAME, POWERTOOLS_METRICS_NAMESPACE, POWERTOOLS_LOG_LEVEL, POWERTOOLS_LOGGER_SAMPLE_RATE, POWERTOOLS_LOGGER_LOG_EVENT, POWERTOOLS_TRACE_DISABLED, POWERTOOLS_METRICS_DISABLED, POWERTOOLS_IDEMPOTENCY_DISABLED.function_name, memory_limit_in_mb, invoked_function_arn and aws_request_id; build a small dataclass in tests.POWERTOOLS_TRACE_DISABLED=1 and POWERTOOLS_METRICS_DISABLED=1 in unit tests so Tracer and Metrics do not try to reach X-Ray or print EMF.app.resolve(event, context) with a dict from the AWS sample events, or HttpResolverLocal to run them under uvicorn locally.The references are generated from the documentation by scripts/build_agent_skill_references.py; the documentation at https://docs.powertools.aws.dev/lambda/python/latest/ is the source of truth.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub aws-powertools/powertools-lambda-python --plugin powertools-lambda-pythonOther plugins' skills for the same job