Post/Code

HomeAboutUsesNow

Using Decorators with Flask-RESTplus.

On a recent project, I have been using Flask-RESTplus for building and auto-documenting an API. Flask-RESTplus comes with Swagger integration out the box and works in a similar way to Flask-RESTful.

Unlike Flask, which uses decorators with functions to describe API resources. Flask-RESTplus (and Flask-RESTful) use Python classes along with decorators to represent your API resources.

I had a decorator from a previous Flask project that I wanted to re-use in my Flask-RESTplus API and was curious about how easily the implementation would carry over. The decorator (@requires_auth) checks that the user is authorised in order to view the endpoint.

In Flask, this would look something like this:

...
@app.route('/protected-resource', methods=['GET'])
@requires_auth('get:protected-resources')
def retrieve_protected(payload):
    try:
        ...
    except AuthError:
        abort(401)

...

As you can see, the route and methods are specified in the route decorator and the functionality is then defined in a function.

To achieve the same result in Flask-RESTplus, you would do the following with the route specified in the decorator and the class using functions to define the API methods:

...
@api.route("/protected")
class Protected(Resource):
    @requires_auth("get:protected-resources")
    def get(self, payload):
        try:
            ...
        except AuthError:
            return abort(401)
...

I find this approach makes organising the routes a little more logical since you can group all the required API methods (GET, POST, DELETE, PUT etc) for a resource together in one class.

As you can see, the approaches are similar but slightly different. You still need to decorate the function defining the route.

If you try to apply the decorator to the class, you will get an error saying: AttributeError: 'function' object has no attribute 'as_view'

There you have two ways of using the same decorator with Flask or Flask-RESTplus.