Search code examples
amazon-web-serviceslambda

How to decorate a function using two routes using AWS Lambda Powertools Event Handler feature?


How can I use the API Gateway Event handler feature of AWS Lambda Powertools to provide two different paths for the same function?

Normally, I would decorate my function as follows, which would allow me to call it using the /v2/application/blacklist path:

@app.post("/v2/application/blacklist")
def post_application_blacklist_v2(body: CurrentVersion) -> ForceUpdate:
   ...

Is there a way to provide multiple paths for a single function, so that I could call the above function as /application/blacklist and /v2/application/blacklist?

I have looked at the documentation, and while it supports dynamic routes, e.g. /order/<id>, it doesn't seem like I can use wildcards.

https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/


Solution

  • You can use a "catch all route" regex as described in https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/#catch-all-routes

    so something like this, using a regular python regex, should work (might need to play with it):

    @app.post("^/(?:v2/)?application/blacklist$")
    def post_application_blacklist_v2(body: CurrentVersion) -> ForceUpdate:
       ...
    

    edit

    depending on your use case, normally I'd recommend setting up a proxy rule at your gateway/load balancer level to forward the request to appropriate v2 endpoint rather than handling in potentially many function decorators.