Skip to content

Feature request: APIGatewayRestResolver decorator support for class methods (use case: constructor injection) #1696

Description

@harwoodjp

Use case

I'd like to decorate class methods with APIGatewayRestResolver's router.

Particularly, I want to use constructor injection in my app. Support dependency injection in lambda parameters is good prerequisite reading.

Here is illustrative code. We have a GET that queries Dynamo with animal_id and returns a JSON response:

class App:
    resolver = APIGatewayRestResolver()

    def __init__(
            self,
            dynamo_client: DynamoClient = DynamoClient(ANIMAL_TABLE)
    ):
        self.dynamo_client = dynamo_client

    @resolver.get("/animal/<animal_id>")
    def get_animal(self, animal_id):
        result = self.dynamo_client.get_item_by_key("animal_id", animal_id)
        payload = json.dumps(result.get("data", []))
        return Response(
            status_code=HTTPStatus.OK,
            content_type=content_types.APPLICATION_JSON,
            body=payload,
        )

def lambda_handler(event, context):
    return App().resolver.resolve(event, context)

Currently I get the following error:

missing 1 required positional argument: 'self'

which indicates self argument isn't being passed. So I believe APIGatewayRestResolver router can't decorate class methods.

Solution/User Experience

Solution is probably:

  • Configure the decorator to pass self

Alternative solutions

Another solution is to simply use method injection as described by @heitorlessa in Support dependency injection in lambda parameters. This negates the benefits of constructor injection, which is useful when multiple methods share a client, for example.

Acknowledgment

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions