Skip to content

feat(event_handler): support Depends() injection in function-based middleware - #8573

Merged
leandrodamascena merged 4 commits into
aws-powertools:developfrom
abhinavs1920:feat/middleware-depends
Oct 18, 2026
Merged

leandrodamascena merged 4 commits into
aws-powertools:developfrom
abhinavs1920:feat/middleware-depends

Conversation

@abhinavs1920

Copy link
Copy Markdown
Contributor

Issue number: closes #8348

Summary

Changes

Function-based middleware can now declare Depends() parameters and a Request parameter, the same way route handlers can:

  • MiddlewareFrame (sync) and AsyncMiddlewareFrame (async, both the coroutine and sync-in-thread paths) resolve Depends() parameters before calling the middleware.
  • The per-request dependency cache is stored in app.context and shared with the route adapters, so a dependency used by both middleware and route is resolved only once.
  • dependency_overrides and Request injection work for middleware dependencies.
  • A middleware that short-circuits never triggers route dependency resolution.
  • Signature inspection is cached on the callable, mirroring Route's caching, so there is no per-request overhead.
  • Class-based middleware is intentionally out of scope for this PR, as discussed on the issue.

User experience

Before: a middleware declaring Annotated[UserDao, Depends(get_user_dao)] was called without that parameter being resolved, so the pattern from the issue (DAO injection into middleware) did not work.

After: the issue's example works as written - the dependency is resolved and injected, and shares its cache with route dependencies.

Testing

  • 9 new tests in tests/functional/event_handler/required_dependencies/test_middleware_depends.py covering the acceptance criteria from the issue discussion: overrides, Request injection, sync + async middleware, short-circuit, single resolution across middleware and route, plus the issue's DAO example and a no-dependency backwards-compat check.
  • tests/functional/event_handler/required_dependencies/: 511 passed.
  • Full tests/functional/event_handler/ suite: passes except 2 failures in _pydantic/test_http_resolver_pydantic.py ASGI concurrency tests, which also fail on unpatched develop (pre-existing, unrelated).

@leandrodamascena - opening this early draft as you offered. Happy to iterate.


By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

…ddleware

Resolve Depends() parameters and Request injection for function-based
middleware in MiddlewareFrame and AsyncMiddlewareFrame, sharing the
per-request dependency cache via app.context so a dependency used by both
middleware and route is resolved only once.

Class-based middleware is intentionally out of scope for this change.

Refs aws-powertools#8348
@powertools-for-aws-oss-automation powertools-for-aws-oss-automation Bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Oct 17, 2026
@boring-cyborg

boring-cyborg Bot commented Oct 17, 2026

Copy link
Copy Markdown

Thanks a lot for your first contribution! Please check out our contributing guidelines and don't hesitate to ask whatever you need.
In the meantime, check out the #python channel on our Powertools for AWS Lambda Discord: Invite link

@leandrodamascena

Copy link
Copy Markdown
Contributor

Hey @abhinavs1920, this looks great, thanks for the quick turnaround! I ran it locally with a few extra scenarios and it all holds up.

Before you take it out of draft, could you add a short section to the docs ("Combining middleware and Depends()" in api_gateway.md, the DAO example from the issue is perfect there), fix the truncated PR title, and add two tests for Router-level and route-level middleware with Depends? Then ping me and I'll do the final review.

@boring-cyborg boring-cyborg Bot added the documentation Improvements or additions to documentation label Oct 18, 2026
@abhinavs1920 abhinavs1920 changed the title feat(event_handler): support Depends() injection in function-based mi… feat(event_handler): support Depends() injection in function-based middleware Oct 18, 2026
@abhinavs1920

Copy link
Copy Markdown
Contributor Author

Thanks for the quick look! All three are in: the docs section with the DAO example from the issue, the title is fixed, and there are now tests for Router-level and route-level middleware with Depends (required_dependencies suite still green). Ready for your final review whenever works.

@codecov

codecov Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.93%. Comparing base (bdd370b) to head (748684f).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #8573   +/-   ##
========================================
  Coverage    96.93%   96.93%           
========================================
  Files          318      318           
  Lines        16005    16031   +26     
  Branches      1420     1423    +3     
========================================
+ Hits         15514    15540   +26     
  Misses         349      349           
  Partials       142      142           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@leandrodamascena
leandrodamascena marked this pull request as ready for review October 18, 2026 11:03
@leandrodamascena
leandrodamascena requested a review from a team as a code owner October 18, 2026 11:03
@leandrodamascena
leandrodamascena self-requested a review October 18, 2026 11:03

@leandrodamascena leandrodamascena left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @abhinavs1920, this came out really well. I ran it with the current develop merged in and a few extra cases on top of your tests: forward-ref annotations, class-based middleware, functools.partial, bound methods, **kwargs, Request with validation on, and a ServiceError raised inside a middleware dependency, which now returns 401 thanks to #8568. All good. I pushed a small test for the bound-method path to cover the last two lines codecov flagged. Approving.

@sonarqubecloud

Copy link
Copy Markdown

@leandrodamascena
leandrodamascena merged commit 0f64f28 into aws-powertools:develop Oct 18, 2026
15 checks passed
@boring-cyborg

boring-cyborg Bot commented Oct 18, 2026

Copy link
Copy Markdown

Awesome work, congrats on your first merged pull request and thank you for helping improve everyone's experience!

@powertools-for-aws-oss-automation

Copy link
Copy Markdown

Awesome work, congrats on your first merged pull request and thank you for helping improve everyone's experience!

@abhinavs1920

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, and for adding the bound-method test to close out the codecov gaps. Enjoyed working through this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation event_handlers size/L Denotes a PR that changes 100-499 lines, ignoring generated files. tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: Make Dependency Injection work for Middleware

2 participants