Post/Code

HomeAboutUsesNow

Flask-RESTplus Authorisation Headers.

Flask-RESTplus comes with built-in Swagger integration. It is however, not entirely obvious how to specify what Authorisation is required via the Swagger UI (at least it was not to me).

If we assume that we have already setup our routes, Swagger and authorisation logic setup. What we now want to do is represent in the Swagger UI which routes requires authorisation via a JSON Web Token (JWT) passed in an Authorisation header. This will enable the user to make the necessary request via the Swagger UI. In order to set this up, you would do as follows:

...

RESTAURANT = api.model(...)

...

# api is our namespace

...

parser = api.parser()
parser.add_argument("Authorisation", location="headers", help="Bearer token required")

...

@api.route("/")
class RestaurantList(Resource):
    def get(self):
        """List all restaurants"""
        return get_restaurants(), 200

    # combine parser, expected model and validation flag 
    # to specify which extra arguments are required, the 
    # shape of expected data and whether to validate that data
    
    @api.expect(parser, RESTAURANT, validate=True)  
    
    # expected responses
    
    @api.response(201, "Restaurant was added!")
    @api.response(400, "Invalid payload")
    @api.response(401, "Unauthorised")
    @api.response(403, "Forbidden")
    @requires_auth("create:restaurant")
    def post(self, payload):
        """Create Restaurant"""
        
        ...

    ...

@api.route("/<int:restaurant_id>")
class Restaurants(Resource):
    
    ...

    # Unlike this post route above, in this case, 
    # we only pass an id to the delete route and 
    # do not require a data payload. However, we 
    # still require the authorisation header by 
    # which to authorise access to the route. Note
    # that in both case, "payload" must be passed
    # as the 2nd parameter after self and before 
    # the id, if one is used.
    
    @api.expect(parser)
    @requires_auth("delete:restaurant)
    def delete(self, payload, wakepark_id):
        """Deletes a single restaurant"""
        
        ...
    
    ...

In the above code, once your imports, namespace and models are setup, you need to define a parser and then use add_argument to add the field necessary("Authorisation") along the location("headers") in which the field should appear as well as some "help" text to describe it.

You then add your parser, along with your model and your validate flag in the @expect decorator. This will add the necessary Authorisation header field to the Swagger UI and will enable you to add your JSON Web Token to the request when making a POST request via the Swagger UI.