NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI
PyPI, #977 most downloaded on PyPI
Powertools for AWS Lambda (Python) is a developer toolkit to implement Serverless best practices and increase developer velocity.
Latest stable
3.40.0
Last release 12 days ago
10 Nov 2026
Ships fairly regularly
a new release about every 4 weeks
Nearly every release is documented
notes for 58 of the last 60 stable releases
3 versions withdrawn
withdrawn after publishing
7 years old
535 releases · first in 2019
Drag across the ruler to compare, or tap a release to open it.
Sixteen bug fixes across Data Masking, Batch, Idempotency, Kafka, Parser, Event Handler, Feature Flags and Data Classes, Amazon Connect Outbound Campa
Sixteen bug fixes across Data Masking, Batch, Idempotency, Kafka, Parser, Event Handler, Feature Flags and Data Classes, Amazon Connect Outbound Campaigns as a new event source, and an Agent Skill so coding assistants build Lambda functions with Powertools the way the docs describe.
One week after 3.39.0 and the community is still carrying the release: fifteen community PRs from eight people. Welcome to our four new contributors: @anishmehta24, @soujasK, @thebadalov and @Goldloli. Thanks to @ASHMEET555, @alphasafal, @azmi2409 and @ShussMiao for coming back, and to @LemonCondor, @Manishram-ai, @AtulJoshi1206 and @ibrhmyi for the reports.
Reminder: we stop supporting Python 3.10 on February 1, 2027. Details in #8735.
After a report that a payload referencing the same object twice came back with the second copy unmasked, we went through erase() end to end. Every case where it returned something the docs say it masks is fixed: repeated objects and __slots__, Pydantic SecretStr/SecretBytes and UUID/datetime/Decimal fields, masking_rules on a JSON string or pointing at a dict or list, fields and masking_rules passed together (now DataMaskingError), Enum values, and every AWS Encryption SDK error on decrypt surfacing as DataMaskingDecryptValueError.
Behaviour change, on purpose. A regex_pattern + mask_format rule whose pattern does not match now masks the whole value. Before, the value came back untouched. A field under a rule is sensitive; returning it in clear because it had an unexpected shape is a leak, not a contract. If you relied on non-matching text passing through, check the match before calling erase. Thank you @LemonCondor.
ConnectOutboundCampaignsEvent in Data Classes and ConnectOutboundCampaignsEventModel in Parser. Declare CustomerData as Json[YourModel] to have it decoded and validated. Thank you @ASHMEET555..agents/skills/, a SKILL.md plus one reference per utility generated from the docs, so an assistant writes the same code the docs show. Install instructions in the README.ValidationError is reported, not the whole batch; SqsFifoPartialProcessor does the same for short-circuited records. Thank you @soujasK.0, False, "", [], {}) are replayed instead of None; the Redis layer keeps the payload hash on completion. Thank you @thebadalov."" (@ASHMEET555).CloudWatchLogsEnvelope accepts plain text lines with model=str (@azmi2409). VpcLatticeV2Model types headers and query strings as dict[str, list[str]], the shape the service sends; hand-written events with plain strings no longer validate. VPCLatticeV2Resolver with validation handles the list-valued Content-Type. Reported by @Manishram-ai and @AtulJoshi1206.SameSite.DEFAULT_MODE leaves the attribute out; compressed routes send Vary: Accept-Encoding.SCHEDULE_BETWEEN_DAYS_OF_WEEK matches by weekday index, so it works with any LC_TIME.SQSMessageAttribute returns None for the value the type does not carry; TransferFamilyAuthorizer.password is None without a password; AppSyncResolverEvent.identity returns AppSyncIdentityLambda for AWS_LAMBDA authorization (@Goldloli, @ShussMiao, @ibrhmyi).Five of those were reported and fixed by @anishmehta24 in two days. Thank you.
@alphasafal, @anishmehta24, @ASHMEET555, @azmi2409, @dreamorosi, @Goldloli, @leandrodamascena, @ShussMiao, @soujasK, @thebadalov and @dependabot[bot]
Your coding agent can read these notes before it upgrades. Set up the MCP server →
One heads-up: Python 3.10 reached end of life and Lambda deprecated the python3.10 runtime on October 31, 2026. We stop supporting Python 3.10 on Febr…
This release fixes seventeen bugs across Parameters, Event Handler, Circuit Breaker, Parser, Data Classes and the shared cache, and corrects a handful of docs. There are only a small new feature, but no new utility this time: we spent the cycle paying down the bugs we had found in our own audits, and the community did most of the paying.
The community is still on fire. We opened the audit findings as good first issue on a Saturday, and by Monday every one of them had a pull request. Nineteen PRs merged, sixteen people, one of them for the third release in a row. Thank you all.
Welcome to our fourteen new contributors: @yagruda, @wanjinhao1, @Golden007-prog, @SuellenQwQ, @MrForward, @Tanmay-Ts, @kudala-bharani, @Suraj1347, @SpinachDigital, @jasperdingg, @Vl4dC, @ShussMiao, @ASHMEET555 and @Manishram-ai. Thanks also to @SumiRann1 for finishing the cache key work started in 3.38.0, and to @vishwakt for a third fix in a row.
One heads-up: Python 3.10 reached end of life and Lambda deprecated the python3.10 runtime on October 31, 2026. We stop supporting Python 3.10 on February 1, 2027. Details and the command to list your functions still on it are in #8735.
Eight fixes, most of them the long tail of get_parameters_by_name and caching after the 3.38.0 changes:
get() and get_parameters_by_name() now share cache entries: a parameter fetched one way is served from cache the other way, and a SecureString fetched with decrypt=True is never served to a call without it.set_parameter and set_secret invalidate the cached value, so the next read returns what you just wrote instead of the old value for up to max_age.get_parameters_by_name with raise_on_error=False lands in _errors and is not cached, so a corrected parameter stops returning None until the cache expires. Note for anyone who checked for None: the failed name is now omitted from the result instead.GetSecretError is a subclass of GetParameterError, so one except GetParameterError covers secrets too.GetParameters client error is wrapped as GetParameterError (or listed in _errors), not only InvalidKeyId and InternalServerError.DynamoDBProvider raises GetParameterError with a clear message for a missing item or a wrong sort_attr, instead of KeyError; the AppConfig provider says which configuration is empty.SecretBinary that is not valid UTF-8 stays bytes without a transform and raises TransformParameterError with one, instead of UnicodeDecodeError.SecretsProvider.get_multiple no longer appends to the Filters list you pass in.list[str] headers accept comma-separated values, repeated header lines are joined for scalar parameters, and +json media types such as application/problem+json are accepted as JSON bodies.Query() and Header() fields render their real types, ValidationError no longer requires a msg it does not emit, Path(alias=...) validates and renders by the template name, and non-finite Decimal values raise SerializationError. An openapi_extensions key without the x- prefix now emits a PowertoolsUserWarning; it becomes an error in the next major.application/json; the AppSync Events registry returns the function when the path is invalid; the AppSync resolver clears its context even when an exception handler answers; Router warns on duplicate routes like the resolver does; and Depends(SomeClass) injects Request and nested dependencies declared on __init__.AppSyncEventsResolver with aggregate=False re-raises UnauthorizedException, so AppSync returns 401 instead of a 200 with an error payload. Class-based middlewares with an async handler are awaited under resolve_async.HttpResolverLocal works as a Lambda handler for REST, HTTP API v2 and Function URL events, not only as an ASGI app.@circuit_breaker now supports async def functions. The coroutine is awaited inside the circuit, so failures count towards failure_threshold, probes run on the awaited result, and on_circuit_open can be a coroutine function. While testing it we also found that concurrent coroutines in one event loop could all run the half-open probe at once, because the probe owner id is per thread; a probe now runs once per process, and the other callers get the open response, the same guarantee threads already had. Thank you @ASHMEET555.
LRUDict.get honours its default and refreshes recency, so falsy cached values are returned and the least recently used entry is the one evicted.CloudWatchAlarmMetric.metric_stat returns None for metric math expression entries instead of raising.aws_lambda_powertools.utilities.parser.models like every other built-in model.a6e34c5 to f17ec84 in /docs (#8737) by @dependabot[bot]a6e34c5 to f17ec84 in /docs (#8737) by @dependabot[bot]@ASHMEET555, @Golden007-prog, @jasperdingg, @kudala-bharani, @leandrodamascena, @Manishram-ai, @MrForward, @ShussMiao, @SpinachDigital, @SuellenQwQ, @SumiRann1, @Suraj1347, @Tanmay-Ts, @vishwakt, @Vl4dC, @wanjinhao1, @yagruda, @dependabot[bot] and @claude
Idempotency: CachePersistenceLayer reads the expiry from the configured expiry_attr and no longer emits the Redis deprecation warning when you use the…
This release adds support for the new Amazon EventBridge Custom Event Bus in Data Classes and Parser, and fixes twenty bugs across Parameters, Event Handler, Idempotency, Logger, Data Classes and Parser.
Almost every fix here came from the community. We opened the bugs we found as good first issue and people picked them up faster than we could review them. Thank you, this is the best part of the job.
Welcome to our thirteen new contributors: @Thanatos9404, @SumiRann1, @proton0210, @azmi2409, @mayuriphad, @MTirnova, @hiyouwhatsapp, @MrNK2107, @sebxt, @codewithzubair07, @Oakcube4life, @Asymtode712 and @alphasafal. Thanks also to @LuisFigueroaG for coming back with another fix.
AWS launched a new EventBridge bus, the Custom Event Bus, with subscribers instead of rules, event retention, ordered delivery per event group, replay, and a PutRawEvents API for Avro, Protobuf and raw bytes. The classic bus is still there, now called Custom Event Bus - Classic.
The new bus delivers events to Lambda in a different shape: a JSON array by default, and a Data / Metadata / SystemMetadata envelope when the subscriber uses the WITH_METADATA transformer. The existing EventBridgeEvent data class and EventBridgeModel only understand the classic single envelope, so we added new ones.
EventBridgeV2Event accepts a single object or an array, with or without metadata, and always exposes a list of records:
from aws_lambda_powertools.utilities.data_classes import EventBridgeV2Event, event_source
@event_source(data_class=EventBridgeV2Event)
def lambda_handler(event: EventBridgeV2Event, context):
for record in event.records:
if record.system_metadata.delivery_type == "REPLAY":
continue
process(record.detail or record.data)
Two things to know before you migrate to EventBridgeV2. The Lambda runtime's bundled boto3 does not have the eventbridgev2 client yet, so publishing to the new bus from inside a function requires packaging boto3 1.43.102 or newer. And we have not added BatchProcessor support for this bus yet: in our tests a partial batch response was not applied by the service, so for now treat each delivery as all-or-nothing and raise if any record should be retried. Thank you @Asymtode712 for the implementation and @alphasafal for the octet-stream fix that followed.
Nine fixes in Parameters, most of them around get_parameters_by_name and caching:
get("/x") and get("/x", decrypt=True) no longer return each other's value.get_parameters_by_name supports version and label selectors ("/param:3", "/param:prod"), no longer mutates the dictionary you pass in, and raises GetParameterError when GetParameters fails in fail-fast mode.get_secrets_by_name returns only the names you asked for, instead of every secret sharing the prefix.get_app_config keeps one provider per environment and application instead of returning the first one for every call.strip_prefixes strip only a leading match, Accept-Encoding: gzip;q=0 disables compression, bytes bodies with a JSON content type are base64 encoded, content-type is matched in any casing, and responses echoing a specific origin carry Vary: Origin.CachePersistenceLayer reads the expiry from the configured expiry_attr and no longer emits the Redis deprecation warning when you use the new name.use_datetime_directive with %F no longer adds milliseconds twice.@alphasafal, @Asymtode712, @azmi2409, @codewithzubair07, @hiyouwhatsapp, @leandrodamascena, @LuisFigueroaG, @mayuriphad, @MrNK2107, @MTirnova, @Oakcube4life, @proton0210, @sebxt, @SumiRann1, @Thanatos9404, @dependabot[bot] and @codewithzubair07
This release adds support for the AppConfig Agent Lambda extension in Parameters and Feature Flags, brings `Depends()` injection to middlewares in Eve
This release adds support for the AppConfig Agent Lambda extension in Parameters and Feature Flags, brings Depends() injection to middlewares in Event Handler, and ships the Lambda layer with precompiled bytecode for faster cold starts. It also fixes bugs across Event Handler, Streaming, Idempotency, Circuit Breaker, Data Classes and Parser.
We are happy to welcome seven new contributors in this release: @abhinavs1920, @AtulJoshi1206, @unknownhackerworld, @LuisFigueroaG, @ArfiArfath21, @vyrnsynx and @reginaldalfret. Thank you for the reports, the fixes and the patience during reviews. Thanks also to @LemonCondor, @xili-ytl, @chiruu12 and @exg for coming back with more.
The AppConfig Agent runs as a Lambda extension next to your function, polls AppConfig for you and serves the configuration over localhost. Reading from it takes a couple of milliseconds instead of a round trip to the service, and your function doesn't need an SDK client for it.
You can now read from the extension with AppConfigExtensionProvider:
from aws_lambda_powertools.utilities.parameters import AppConfigExtensionProvider
provider = AppConfigExtensionProvider(environment="prod", application="orders")
config = provider.get("features", transform="json")
Feature Flags support it too. Pass use_extension=True to AppConfigStore, or use AppConfigExtensionStore:
from aws_lambda_powertools.utilities.feature_flags import AppConfigExtensionStore, FeatureFlags
store = AppConfigExtensionStore(environment="prod", application="orders", name="features")
feature_flags = FeatureFlags(store=store)
The extension is configured through its own environment variables, such as AWS_APPCONFIG_EXTENSION_PREFETCH_LIST and AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS, and you attach the AWS-AppConfig-Extension layer to your function. The docs list the variables and the layer ARNs.
Function-based middlewares can now declare Depends() parameters, the same way route handlers do. Dependencies are resolved before the middleware runs, share the per-request cache with the route, and honour dependency_overrides in tests.
def user_middleware(
app: APIGatewayHttpResolver,
next_middleware: NextMiddleware,
user_dao: Annotated[UserDao, Depends(get_user_dao)],
):
sub = app.current_event.request_context.authorizer.jwt_claim.get("sub")
if sub and (user := user_dao.get(sub)):
app.append_context(user=user)
return next_middleware(app)
app.use(middlewares=[user_middleware])
Exceptions raised inside a dependency are now handled like exceptions raised by the route: a ServiceError becomes the matching HTTP response and your exception_handler runs. Thank you @abhinavs1920 for the middleware support and @AtulJoshi1206 for the exception handling.
The Lambda layer now ships precompiled bytecode for every module, so Python skips compilation on cold start. Nothing changes in how you use the layer; it grows a few megabytes. Parser event models are also loaded on demand now, so importing aws_lambda_powertools.utilities.parser.models no longer builds every model up front.
This release ships a new Auth utility in alpha, with two pieces: a JWT verifier to protect your APIs and an OAuth2 client to call APIs protected by so
This release ships a new Auth utility in alpha, with two pieces: a JWT verifier to protect your APIs and an OAuth2 client to call APIs protected by someone else. It also fixes a handful of bugs across Data Classes, Streaming, Idempotency, Event Handler, Metrics and Feature Flags.
A special thank you to @bfreiberg for the outstanding work on both Auth utilities. They helped and implemented them, wrote the docs and tested it.
Welcome also to our other new contributors @Om-singhaI, @Shubham-Padkonde, @chancesong10 and @chiruu12. Thank you for the reports, the fixes and the patience during reviews.
You can now verify access tokens with JWTVerifier. It fetches and caches the issuer's JWKS, selects the signing key, and checks signature, issuer, audience, expiration and any claim you require. Only asymmetric algorithms are accepted, and errors never include token material.
from aws_lambda_powertools.event_handler import APIGatewayHttpResolver
from aws_lambda_powertools.utilities.auth_alpha import JWTVerifier
app = APIGatewayHttpResolver()
verifier = JWTVerifier(
issuer="https://idp.example.com",
audience="https://orders.example.com",
algorithms=["RS256"],
required_claims=["sub"],
)
@app.get("/orders", middlewares=[verifier.require(scopes=["orders:read"])])
def list_orders():
return {"subject": app.context["claims"]["sub"]}
The middleware returns 401 for missing or invalid tokens and 403 for missing scopes. You can also call verifier.verify(token) directly, use verifier.authorize(event) inside an API Gateway Lambda authorizer, or start from JWTVerifier.cognito() for Amazon Cognito access tokens.
Install it with pip install "aws-lambda-powertools[jwt]". Thank you @bfreiberg for building this with us.
You can now call downstream APIs protected by OAuth2 with OAuth2Client. It exchanges your client credentials for a bearer token, caches it, and refreshes it before it expires. Pass the client secret as a callable and it is loaded on every exchange, so it can come straight from Secrets Manager.
from aws_lambda_powertools.utilities.auth_alpha import OAuth2Client
inventory_api = OAuth2Client(
token_url="https://idp.example.com/token",
client_id="orders-service",
client_secret=load_secret,
scopes=["inventory:read"],
)
response = inventory_api.request("GET", "https://inventory.example.com/stock/sku-123")
Use auth_headers() instead if you want only the Authorization header for your own HTTP client.
Install it with pip install "aws-lambda-powertools[oauth2]".
Both utilities live under auth_alpha while we collect feedback, so the API may change before GA. Pin your Powertools version if you use them in production. They are included in the Lambda layer.
@bfreiberg, @chancesong10, @chiruu12, @ericbn, @leandrodamascena, @Om-singhaI, @Shubham-Padkonde, @dependabot[bot] and @claude
This release includes an important security improvement for Data Masking and a significant cold start optimization for Parser.
This release includes an important security improvement for Data Masking and a significant cold start optimization for Parser.
We are happy to welcome six new contributors in this release: @Adityaj0, @manshahH, @ErezMizrahi, @wuodar, @MohammedAlkindi, and @TanbirRamim. Thank you for taking the time to report problems, work through reviews, and improve the prokject.
Previously, an error while applying a masking rule could emit a warning and return the original value unchanged. Since callers received a normal return value, they could continue logging or storing data believing that masking had succeeded.
Data Masking now raises DataMaskingError when a masking provider fails, a masking path is invalid, or a regular expression cannot be compiled. Existing Data Masking exceptions now inherit from this common base exception.
from aws_lambda_powertools.utilities.data_masking import DataMasking
from aws_lambda_powertools.utilities.data_masking.exceptions import DataMaskingError
data_masker = DataMasking()
try:
masked = data_masker.erase(
{"customer": {"email": "customer@example.com"}},
masking_rules={"customer.email": {"regex_pattern": "[", "mask_format": "*"}},
)
except DataMaskingError:
# Stop processing the payload when masking cannot be completed.
raise
Missing fields continue to follow the existing raise_on_missing_field setting. With its default value, a missing field raises DataMaskingFieldNotFoundError; when explicitly disabled, Data Masking emits a warning and continues.
See #8446 for the complete change.
Importing parse or event_parser previously loaded all 16 Parser envelope modules, even when the application did not use an envelope.
Envelopes and BaseEnvelope are now loaded only when first accessed. Existing public imports continue to work, so no application changes are required.
In the Lambda benchmark contributed in #8405, this reduced INIT_DURATION by approximately 900ms on arm64 with Python 3.13 and 1024MB of memory. The exact improvement depends on the function and packaging configuration.
Thank you @ErezMizrahi for finding this and working through the compatibility details with us.
@Adityaj0, @amin-farjadi, @dreamorosi, @ErezMizrahi, @leandrodamascena, @manshahH, @MohammedAlkindi, @TanbirRamim, @vishwakt, @wuodar, @dependabot[bot], Amin Farjadi, @claude, emizrahi and @ericbn
We're really happy to say the Circuit Breaker utility is now GA. It shipped as alpha in 3.31.0 to collect real-world feedback, and that's exactly what
We're really happy to say the Circuit Breaker utility is now GA. It shipped as alpha in 3.31.0 to collect real-world feedback, and that's exactly what happened, so it's time to drop the _alpha suffix and call it stable.
A big thank you to everyone who used it, reported issues and sent fixes during the alpha. It's in much better shape because of you.
The only change you need to make is the import path. circuit_breaker_alpha becomes circuit_breaker:
from aws_lambda_powertools.utilities.circuit_breaker import circuit_breaker
from aws_lambda_powertools.utilities.circuit_breaker.persistence import (
CircuitBreakerDynamoDBPersistence,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
persistence = CircuitBreakerDynamoDBPersistence(table_name="CircuitBreakerState")
@circuit_breaker(name="payment-backend", persistence_store=persistence)
def charge(order: dict) -> dict:
return payment_api.charge(order)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return charge(event)
Everything else stays the same. Same API, same defaults (open after 5 consecutive failures, probe after 30 seconds, close after 3 probe successes), same behaviour. If you were using it during the alpha, update the import and you're done.
You'll notice we jumped from 3.31.1 straight to 3.34.0. Nothing to worry about: our release pipeline accidentally skipped 3.32.0 and 3.33.0, so they were never built or published. No package went to PyPI and no Lambda layer was published for either of them, so there's no impact for anyone. Everything that was meant to go out in those two releases is included here in 3.34.0.
@DebadityaHait, @leandrodamascena, @vishwakt and @dependabot[bot]
This release fixes bugs across Circuit Breaker, Event Handler, Parser, and the Event Source data classes. Super thanks to @Iamrodos for running the Ci
This release fixes bugs across Circuit Breaker, Event Handler, Parser, and the Event Source data classes. Super thanks to @Iamrodos for running the Circuit Breaker alpha for real and finding the concurrency and configuration issues fixed here.
@Iamrodos, @amin-farjadi, @dependabot[bot], @exg, @github-actions[bot], @leandrodamascena, @stenczelt, dependabot[bot] and github-actions[bot]
This release adds a new Circuit Breaker utility (in alpha) that stops your Lambda from sending requests to an unhealthy downstream and gives it time t
This release adds a new Circuit Breaker utility (in alpha) that stops your Lambda from sending requests to an unhealthy downstream and gives it time to recover. We also made parameter validation in the Event Handler more flexible, so any Pydantic Field annotation now works with any parameter type.
A huge thanks to everyone who helped shape the Circuit Breaker RFC and reviewed this release!
When a downstream service is failing, retries and Lambda's scaling only make it worse: more clients sending requests to something that is already down. The Circuit Breaker stops sending traffic to an unhealthy dependency, then probes it to see when it is safe to resume.
It ships as circuit_breaker_alpha on purpose. We want about a month of real-world feedback before we lock the public API and promote it to GA.
The smallest setup is a persistence store and a name. You wrap the function that makes the downstream call:
from aws_lambda_powertools.utilities.circuit_breaker_alpha import circuit_breaker
from aws_lambda_powertools.utilities.circuit_breaker_alpha.persistence import (
CircuitBreakerDynamoDBPersistence,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
persistence = CircuitBreakerDynamoDBPersistence(table_name="CircuitBreakerState")
@circuit_breaker(name="payment-backend", persistence_store=persistence)
def charge(order: dict) -> dict:
return payment_api.charge(order)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return charge(event)
With no config, sensible defaults apply: open after 5 failures in a row, probe after 30s, close after 3 successes, and treat any exception as a failure. A few things make it a good fit for Lambda:
When the circuit is open, you decide what happens to the rejected request with an on_circuit_open callback (buffer it, drop it, return a cached value), or let it raise CircuitBreakerOpenError. You can also watch state changes with an on_transition hook to emit your own metrics.
import json
from uuid import uuid4
from aws_lambda_powertools.utilities.circuit_breaker_alpha import circuit_breaker
from aws_lambda_powertools.utilities.circuit_breaker_alpha.persistence import (
CircuitBreakerDynamoDBPersistence,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
persistence = CircuitBreakerDynamoDBPersistence(table_name="CircuitBreakerState")
def buffer_payload(payload: dict, circuit) -> None:
# Circuit is OPEN. The call never ran, so the payload is yours to handle.
s3.put_object(Bucket="payment-overflow", Key=f"{circuit.name}/{uuid4()}", Body=json.dumps(payload))
@circuit_breaker(
name="payment-backend",
persistence_store=persistence,
on_circuit_open=buffer_payload,
)
def charge(order: dict) -> dict:
return payment_api.charge(order)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return charge(event)
You can now use any Pydantic Field annotation with any parameter location (Path, Query, Header, Body), the same way it works inside a model. Before, only Field(discriminator=...) with Body() was supported.
from typing import Annotated
from pydantic import Field
from aws_lambda_powertools.event_handler import APIGatewayHttpResolver
from aws_lambda_powertools.event_handler.openapi.params import Query
from aws_lambda_powertools.utilities.typing import LambdaContext
app = APIGatewayHttpResolver(enable_validation=True)
@app.get("/count")
def get_count(n: Annotated[int, Field(gt=0), Query]): # gt=0 enforced, 422 on n <= 0
return {"count": n}
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context)
Last but not least, thanks to everyone who reported issues and helped us improve this release.
@dependabot[bot], @github-actions[bot], @leandrodamascena, dependabot[bot] and github-actions[bot]
This release adds a custom serializer option to the BedrockAgentResolver, plus documentation improvements and bug fixes across the Event Handler.
This release adds a custom serializer option to the BedrockAgentResolver, plus documentation improvements and bug fixes across the Event Handler.
A huge thanks to @kimnamu, @Avinm and @hirenkumar-n-dholariya for their contributions!
You can now pass your own serializer to BedrockAgentResolver, the same way the other resolvers already allow. This lets you control exactly how responses are serialized to JSON, for example to handle custom types or tune the output format.
import json
from decimal import Decimal
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
def custom_serializer(obj: dict) -> str:
return json.dumps(obj, default=str)
app = BedrockAgentResolver(serializer=custom_serializer)
@app.get("/price", description="Returns the current price")
def get_price() -> dict:
return {"price": Decimal("9.99")}
def lambda_handler(event: dict, context: LambdaContext):
return app.resolve(event, context)
@Avinm, @Sujit-1509, @dependabot[bot], @derdelean, @github-actions[bot], @hirenkumar-n-dholariya, @kimnamu, @leandrodamascena, dependabot[bot] and github-actions[bot]
We're thrilled to announce native async resolution for the Event Handler. Write async def route handlers, call await app.resolve_async(event, context)
We're thrilled to announce native async resolution for the Event Handler. Write async def route handlers, call await app.resolve_async(event, context), and mix sync/async middlewares. Everything runs natively on the event loop.
We also fixed OpenAPI schema generation for Pydantic @computed_field, a deadlock when sync middlewares raised before calling next(), and ALB returning 422 when response body is None.
A huge thanks to @hirenkumar-n-dholariya, @amrabed, and @catarinacps for their contributions!
You can now define async route handlers and resolve them without blocking the event loop.
Even though the Lambda handler itself is sync, you can use asyncio.run(app.resolve_async(event, context)) to fan out multiple I/O calls concurrently with asyncio.gather or call async libraries directly.
import asyncio
from aws_lambda_powertools.event_handler import APIGatewayHttpResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
app = APIGatewayHttpResolver()
async def get_orders(user_id: str) -> list:
...
async def get_profile(user_id: str) -> dict:
...
@app.get("/dashboard/<user_id>")
async def get_dashboard(user_id: str):
orders, profile = await asyncio.gather(
get_orders(user_id),
get_profile(user_id),
)
return {"orders": orders, "profile": profile}
def lambda_handler(event: dict, context: LambdaContext):
return asyncio.run(app.resolve_async(event, context))
Sync and async middlewares work together seamlessly. Sync middlewares are bridged to the event loop in a background thread, so you don't need to rewrite existing middleware to adopt async handlers.
Pydantic @computed_field properties now appear in generated OpenAPI schemas. Previously they were excluded because we always used mode="validation" when generating JSON schemas.
from pydantic import BaseModel, computed_field
from aws_lambda_powertools.event_handler import APIGatewayHttpResolver
app = APIGatewayHttpResolver(enable_validation=True)
class Order(BaseModel):
price: float
quantity: int
@computed_field
@property
def total(self) -> float:
return self.price * self.quantity
@app.get("/order")
def get_order() -> Order:
return Order(price=10.0, quantity=3)
Last but not least, thanks to @chriselion and @avplab for reporting bugs in our Event Handler resolvers.
@amrabed, @catarinacps, @dependabot[bot], @github-actions[bot], @hirenkumar-n-dholariya, @leandrodamascena, dependabot[bot] and github-actions[bot]
This release brings dependency injection, an enriched Request object, OpenAPI improvements, and internal refactoring to the Event Handler.
This release brings dependency injection, an enriched Request object, OpenAPI improvements, and internal refactoring to the Event Handler.
Depends() with nested resolution, caching, and test overridesresolved_event and context properties bridge middleware and dependenciesA huge thanks to @JustinBerger, @Iamrodos, and @ran-isenberg for their contributions!
You can now use Depends() to declare typed dependencies directly in route handler signatures: no decorators, no global state. Dependencies are resolved automatically, cached per invocation, and support nested dependency trees.
import os
from typing import Any
import boto3
from typing_extensions import Annotated
from aws_lambda_powertools.event_handler import APIGatewayHttpResolver
from aws_lambda_powertools.event_handler.depends import Depends
from aws_lambda_powertools.utilities.typing import LambdaContext
app = APIGatewayHttpResolver()
def get_dynamodb_table():
dynamodb = boto3.resource("dynamodb")
return dynamodb.Table(os.environ["TABLE_NAME"])
@app.get("/orders")
def list_orders(table: Annotated[Any, Depends(get_dynamodb_table)]):
return table.scan()["Items"]
For testing, swap any dependency without monkeypatching:
app.dependency_overrides[get_dynamodb_table] = lambda: mock_table
The Request object now exposes resolved_event and context, enabling dependency functions to access the full Powertools event and bridge data with middleware.
from typing_extensions import Annotated
from aws_lambda_powertools.event_handler import APIGatewayHttpResolver, Response
from aws_lambda_powertools.event_handler.depends import Depends
from aws_lambda_powertools.event_handler.request import Request
app = APIGatewayHttpResolver()
# Middleware handles auth: can return HTTP responses (redirects, 401s)
def auth_middleware(app, next_middleware):
token = app.current_event.headers.get("authorization", "")
if not token:
return Response(status_code=401, body="Unauthorized")
app.append_context(user={"id": "user-123", "role": "admin"})
return next_middleware(app)
app.use(middlewares=[auth_middleware])
# Depends() reads what middleware wrote via request.context
def get_current_user(request: Request) -> dict:
return request.context["user"]
@app.get("/admin/dashboard")
def admin_dashboard(user: Annotated[dict, Depends(get_current_user)]):
return {"message": f"Welcome {user['id']}", "role": user["role"]}
You can now set the default response status code directly on route decorators. This is reflected in the generated OpenAPI schema and Swagger UI.
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
app = APIGatewayRestResolver(enable_validation=True)
@app.post(
"/todos",
summary="Creates a new todo item",
status_code=201,
tags=["Todos"],
)
def create_todo(title: str) -> dict:
return {"id": 1, "title": title}
@JustinBerger, @dependabot[bot], @github-actions[bot], @leandrodamascena, dependabot[bot] and github-actions[bot]
In this release, we focused on the Event Handler utility - we added three new features and shipped several important bug fixes across Event Handler an
In this release, we focused on the Event Handler utility - we added three new features and shipped several important bug fixes across Event Handler and Idempotency.
multipart/form-data uploads with full OpenAPI validation and Swagger UI file pickerQuery(), Header(), and Form()A huge thanks to @oyiz-michael, @siwyd, @abhu85, and @danjhd for their contributions!
You can now handle file uploads in your API endpoints with full OpenAPI validation and Swagger UI support. If using Swagger, it renders a file picker automatically. A special thanks to @oyiz-michael for starting the initial work on this feature.
from typing import Annotated
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.openapi.params import File, Form, UploadFile
app = APIGatewayRestResolver(enable_validation=True)
app.enable_swagger(path="/swagger")
@app.post("/upload")
def upload(
file_data: Annotated[UploadFile, File(description="CSV file")],
separator: Annotated[str, Form(description="CSV separator")] = ",",
):
return {
"filename": file_data.filename,
"content_type": file_data.content_type,
"file_size": len(file_data),
}
You can receive files as raw bytes (Annotated[bytes, File()]) or as an UploadFile object with filename and content type metadata.
You can now use cookies as typed, validated parameters in your API endpoints - just like Query(), Header(), or Form(). The OpenAPI schema generates in: cookie parameters automatically, and validation works across all resolver types.
from typing import Annotated
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.openapi.params import Cookie
app = APIGatewayRestResolver(enable_validation=True)
@app.get("/me")
def get_me(
session_id: Annotated[str, Cookie(description="Session identifier")],
theme: Annotated[str, Cookie(description="UI theme")] = "light",
):
return {"session_id": session_id, "theme": theme}
We added a Request object that gives middleware and route handlers access to the resolved route pattern, Powertools-extracted path parameters, HTTP method, headers, query parameters, and body. Previously, middleware only had access to app.current_event, which returns raw API Gateway parameters (e.g. {"proxy": "users/123"} for {proxy+} routes) instead of the resolved ones.
You can access the Request object in two ways:
In middleware via app.request:
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response
from aws_lambda_powertools.event_handler.middlewares import NextMiddleware
app = APIGatewayRestResolver()
def auth_middleware(app: APIGatewayRestResolver, next_middleware: NextMiddleware) -> Response:
req = app.request
route = req.route # "/users/{user_id}"
path_params = req.path_parameters # {"user_id": "123"}
method = req.method # "GET"
# auth logic here...
return next_middleware(app)
app.use(middlewares=[auth_middleware])
In route handlers via type annotation:
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Request
app = APIGatewayRestResolver()
@app.get("/users/<user_id>")
def get_user(user_id: str, request: Request):
user_agent = request.headers.get("user-agent")
return {"id": user_id, "route": request.route, "user_agent": user_agent}
8f41b60 to 868ad4d in /docs (#8083) by @dependabot[bot]8f41b60 to 868ad4d in /docs (#8083) by @dependabot[bot]@abhu85, @danjhd, @dependabot[bot], @github-actions[bot], @leandrodamascena, @oyiz-michael, @ran-isenberg, @siwyd, dependabot[bot] and github-actions[bot]
In this release, we are pleased to announce a new utility for interacting with the Lambda Metadata Service, allowing you to easily retrieve informatio
In this release, we are pleased to announce a new utility for interacting with the Lambda Metadata Service, allowing you to easily retrieve information about the Lambda function, such as the Availability Zone ID.
A huge thanks to @acascell, @shaked-lokits, @maxrabin, and @amin-farjadi, for their contributions 🚀🌟
You can now use get_lambda_metadata() function fetch metadata from the AWS Lambda Metadata endpoint, such as the Availability Zone ID. Results are cached for the sandbox lifetime and the utility automatically returns empty metadata outside of Lambda, so your code works seamlessly in local development and testing.
from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.metadata import LambdaMetadata, get_lambda_metadata
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
def lambda_handler(event: dict, context: LambdaContext) -> dict:
metadata: LambdaMetadata = get_lambda_metadata()
az_id = metadata.availability_zone_id # e.g., "use1-az1"
logger.append_keys(az_id=az_id)
logger.info("Processing request")
return {"az_id": az_id}
@acascell, @amin-farjadi, @dependabot[bot], @github-actions[bot], @leandrodamascena, @shaked-lokits, dependabot[bot] and github-actions[bot]
This release introduces per-route validation support in event handler, durable context support for logger and metric decorators, multiple dimension se
This release introduces per-route validation support in event handler, durable context support for logger and metric decorators, multiple dimension sets in metrics, S3 IntelligentTiering event support, and a URL-decode flag for ALB query parameters. We also shipped several important bug fixes across logger, parameters, event handler, and typing.
A huge thanks to @oyiz-michael, @chriselion, @maxrabin, @facu-01, and @Iamrodos, for their contributions 🚀🌟
You can now enable or disable validation on individual routes. This is useful when migrating incrementally - enable validation globally and opt-out specific legacy routes, or vice versa.
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from pydantic import BaseModel
app = APIGatewayRestResolver(enable_validation=True)
class Todo(BaseModel):
title: str
completed: bool
# This route has validation enabled (inherits from resolver)
@app.post("/todos")
def create_todo(todo: Todo) -> dict:
return {"title": todo.title}
# This route opts out of validation
@app.get("/legacy", enable_validation=False)
def legacy_endpoint():
return {"message": "no validation here"}
Logger and Metrics decorators now handle AWS Lambda Durable Context automatically. When a durable function replays, the decorators unwrap the DurableContext to access the underlying Lambda context - no changes needed in your code.
from aws_lambda_powertools import Logger, Metrics
from aws_lambda_powertools.metrics import MetricUnit
logger = Logger()
metrics = Metrics()
@logger.inject_lambda_context # automatically handles DurableContext
@metrics.log_metrics # automatically handles DurableContext
def lambda_handler(event, context):
logger.info("Processing event")
metrics.add_metric(name="InvocationCount", unit=MetricUnit.Count, value=1)
return {"statusCode": 200}
You can now publish metrics with multiple dimension sets using add_dimensions(). Each call creates a new dimension set in the CloudWatch EMF output.
from aws_lambda_powertools import Metrics
from aws_lambda_powertools.metrics import MetricUnit
metrics = Metrics()
@metrics.log_metrics
def lambda_handler(event, context):
metrics.add_metric(name="OrderCount", unit=MetricUnit.Count, value=1)
# Each call creates a separate dimension set
metrics.add_dimensions(environment="prod", region="us-east-1")
metrics.add_dimensions(service="orders", team="backend")
A new decode_query_parameters flag in ALBResolver automatically URL-decodes query parameter keys and values.
from aws_lambda_powertools.event_handler import ALBResolver
app = ALBResolver(decode_query_parameters=True)
@app.get("/search")
def search():
# Query params are automatically URL-decoded
query = app.current_event.query_string_parameters
return {"query": query}
3bba0a9 to 8f41b60 in /docs (#8010) by @dependabot[bot]3bba0a9 to 8f41b60 in /docs (#8010) by @dependabot[bot]@ConnorKirk, @Iamrodos, @chriselion, @dependabot[bot], @dreamorosi, @facu-01, @github-actions[bot], @leandrodamascena, @maxrabin, @oyiz-michael, dependabot[bot] and github-actions[bot]
Nothing published for this version
This release adds support for Lambda durable function replay in idempotency, a new parser model for DynamoDB Stream on-failure destinations, and a fix
This release adds support for Lambda durable function replay in idempotency, a new parser model for DynamoDB Stream on-failure destinations, and a fix for batch processor. We've also dropped Python 3.9 support.
A super thanks to @ConnorKirk for implementing the idempotency replay feature and @exg for the batch processor fix and DynamoDB Stream parser model 🚀🌟
AWS Lambda durable functions enable you to build resilient multi-step applications that can execute for up to one year while maintaining reliable progress despite interruptions. When a durable function resumes from a wait point or interruption, the system performs replay - running your code from the beginning but skipping completed checkpoints.
This release adds support for durable function replay in idempotency. When using the @idempotent decorator on lambda_handler, replay is automatically detected from the DurableContext - no manual configuration needed.
from aws_lambda_powertools.utilities.idempotency import idempotent, DynamoDBPersistenceLayer, IdempotencyConfig
persistence_layer = DynamoDBPersistenceLayer(table_name="idempotency_store")
config = IdempotencyConfig(event_key_jmespath="body")
@idempotent(config=config, persistence_store=persistence_layer)
def lambda_handler(event, context):
# Replay is automatically detected when context is a DurableContext
# During replay, INPROGRESS records are handled gracefully
return {"statusCode": 200}
A new parser model DynamoDBStreamLambdaOnFailureDestinationModel is now available for parsing DynamoDB Stream on-failure destination events.
from aws_lambda_powertools.utilities.parser import parse
from aws_lambda_powertools.utilities.parser.models import DynamoDBStreamLambdaOnFailureDestinationModel
def lambda_handler(event, context):
parsed = parse(event=event, model=DynamoDBStreamLambdaOnFailureDestinationModel)
batch_info = parsed.ddb_stream_batch_info
print(f"Failed batch from shard: {batch_info.shard_id}")
print(f"Stream ARN: {batch_info.stream_arn}")
BedrockAgentFunctionResolver (#7808) by @dreamorosi980e11f to 3bba0a9 in /docs (#7835) by @dependabot[bot]@ConnorKirk, @Iamrodos, @T90REAL, @dependabot[bot], @dreamorosi, @exg, @github-actions[bot], @leandrodamascena, @nc-dirknilius, @oyiz-michael, dependabot[bot] and github-actions[bot]
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
In this release we added support for the newly released Python 3.14 AWS Lambda managed runtime .
In this release we added support for the newly released Python 3.14 AWS Lambda managed runtime :rocket:.
58dee36 to 980e11f in /docs (#7661) by @dependabot[bot]@ConnorKirk, @Iamrodos, @T90REAL, @dependabot[bot], @dreamorosi, @github-actions[bot], @leandrodamascena, @victorperezpiqueras, dependabot[bot] and github-actions[bot]
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
In this release, we fixed a regression introduced by PR #7227 that affected customers using the Event Handler utility with nested metadata annotations
In this release, we fixed a regression introduced by PR #7227 that affected customers using the Event Handler utility with nested metadata annotations such as annotated_types or Interval. Thanks to @rtandy for identifying the bug and validating the fix.
We also fixed small bugs in type annotations and in our documentation.
⭐ Congrats @rpivo and @czechnology for contributing to this project for the first time!
f5c556a to 58dee36 in /docs (#7622) by @dependabot[bot]@ConnorKirk, @czechnology, @dependabot[bot], @github-actions[bot], @leandrodamascena, @mahveotm, @rpivo, dependabot[bot] and github-actions[bot]
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
This release enhances our Event Handler with support for Pydantic Models when validating query strings and headers parameters. This addition brings ty
This release enhances our Event Handler with support for Pydantic Models when validating query strings and headers parameters. This addition brings type safety, automatic validation, and better developer experience to your API endpoints.
A super thanks to @tonnico for implementing this important feature 🚀 🌟
📜 Announcement: You can now find our documentation on the official AWS documentation domain at docs.aws.amazon.com/powertools/python.
You can now use Pydantic's models to validate query strings and headers parameters. This allows you to have structured, type-safe validation with automatic error handling and clear validation messages.
Why this important:
<img width="1728" height="1422" alt="carbon (19)" src="https://github.com/user-attachments/assets/c64ac0f6-2147-45ec-84fa-ba149d030980" />
examples field in OpenAPI schema for BedrockAgentResolver (#7561) by @leandrodamascena00f9276 to f5c556a in /docs (#7530) by @dependabot[bot]@ConnorKirk, @dependabot[bot], @github-actions[bot], @leandrodamascena, @sthulb, @tonnico, dependabot[bot] and github-actions[bot]
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
This release enhances our Event Handler with support for Pydantic Field discriminators and improved OpenAPI response capabilities. We've also expanded
This release enhances our Event Handler with support for Pydantic Field discriminators and improved OpenAPI response capabilities. We've also expanded our Parser utility with better AppSync and CloudWatch models, plus important bug fixes for form data handling.
⭐️ Congrats to @dap0am, @tonnico, @sreejaaryahi18, @aalvrzf, @Iamrodos, and @dcabib for contributing to this release!
You can now use Pydantic's discriminator feature in your Event Handler validation. This allows you to handle polymorphic data structures with union types more efficiently.
<img width="1728" height="1758" alt="union" src="https://github.com/user-attachments/assets/677a8488-f836-4e05-a5f0-8bde13efbbac" />
The OpenAPI utility now supports richer response definitions including headers, links, examples, and encoding specifications, giving you more control over your API documentation.
86d21da to 00f9276 in /docs (#7452) by @dependabot[bot]209b62d to 86d21da in /docs (#7386) by @dependabot[bot]@Iamrodos, @aalvrz, @dap0am, @dcabib, @dependabot[bot], @github-actions[bot], @hjgraca, @kattakaha, @leandrodamascena, @sreejaaryahi18, @tonnico, dependabot[bot] and github-actions[bot]
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
One column per quarter.