Skip to content

Feature request: Make Dependency Injection work for Middleware #8348

Description

@bdellegrazie

Use case

Hi,

Is there a way to extend the Dependency Injection support for routes to include middleware functions as well? Is this worthwhile?

Middleware is typically used to augment a request with additional data or implement a strict control and this is something that might require data access object (DAO) patterns or similar.

Thoughts?

Thanks in advance,

Brett

Solution/User Experience

Example :

Obviously this is a contrived example. As per the framework it would be possible to return an error response if any lookup failed rather than continuing on as this example does.

def user_middleware(
    app: APIGatewayHttpResolver,
    next_middleware: NextMiddleware,
    user_dao: Annotated[UserDao, Depends(get_user_dao)],
) -> Response:
    authorizer = app.current_event.request_context.authorizer
    if authorizer:
        sub: str | None = app.current_event.request_context.authorizer.jwt_claim.get("sub")
        if sub:
            user = user_dao.get(sub)
            if user:
                app.append_context(user=user)
    return next_middleware(app)

Alternative solutions

Acknowledgment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature-requestfeature requesttriagePending triage from maintainers

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions