Search code examples
pythonpython-3.xflaskflask-restful

Interceptor or filter for rest endpoint


I just complete my python flask 101 tutorial here. All went well and now I have flask server running successfully.

However, now I want to add another rest endpoint /products that should return a sample list of products in this case. Since it is a jwt based implementation, I would like to make sure the user request is intercepted by /status or /auth api before it is executed.

Is there a way to reuse current implementation rather than copy pasting the whole thing again for new rest endpoints?


Solution

  • There are two ways you can do this.

    The first one is a little implicit. It's possible to specify methods that should be called before and after requests.

    @app.before_request
    def authenticate():
        # logic for verifying tokens
        pass
    

    The authenticate function would be called for each route.

    Documentation

    Documentation

    On the other hand you can create a view decorator:

    from functools import wraps
    
    def requires_auth(view):
        @wraps(view)
        def decorated(*args, **kwargs):
            # logic for verifying tokens
    
            return view(*args, **kwargs)
    
        return decorated
    

    and then you can wrap any view that should be protected with this decorator E.g

    @requires_auth
    @app.route('/myroute')
    def my_route():
        # Normal logic for view
        pass
    

    It depends on your use case, if your Flask app is an API where most of the views are protected you can go with the .before_request method on the other hand if you have a lot of pages that are public. You can use the decorator.