aws / chalice

Python Serverless Microframework for AWS
Apache License 2.0
10.61k stars 1.01k forks source link

Feature Request: Expose matched URL pattern on Request object #1483

Open bjmc opened 4 years ago

bjmc commented 4 years ago

Hello,

I'm building a REST API with Chalice and I'm using OpenAPI 3 to document the API and validate incoming requests. In order to find the right validations to enforce, it's necessary to compare an incoming request against the specification document, and match the right URL pattern. Today, this is hard to do with Chalice because the Request object doesn't expose the URL pattern of the route handling that request.

The Chalice app does have this information (because it needs to find the right decorated function to call) but it's hard to access from inside the function.

I'm imagining something like this:

@app.route('/hello/{name}')
def hello(name):
    return {'pattern': app.current_request.matched_url_pattern,
            # For extra credit (I know path is in the context already):
            'path': app.current_request.path}

# GET /hello/brendan would return:
# {
#     'pattern': '/hello/{name}',
#     'path': '/hello/brendan'
# }

(obviously in this silly trivial case I could just assign '/hello/{name}' to a variable and use it both places)

I happen to be using this library but the feature I'm asking for would be library agnostic.

Thanks for all your work on Chalice!

jamesls commented 4 years ago

This should be doable since the URL router should know what pattern it matched. Marking as a feature request.

bjmc commented 3 years ago

Possibly related to #485

bhrutledge commented 2 years ago

Possibly related to #906. This might allow using something like https://github.com/p1c2u/openapi-core (which already has integrations for other frameworks) to validate requests based on an existing OpenAPI spec.