Flask-restful: Best way to add custom headers ?

Created on 7 May 2013  Â·  4Comments  Â·  Source: flask-restful/flask-restful

Hi,

I looked at the source code and am wondering what is the suggested way to add custom headers to the API responses.

Thanks for any pointer.

Most helpful comment

Why not add the custom headers to your resource's endpoint return value?

class User(Resource):
    def get(self):
        # Some code
        return {'id': 1, 'name': 'John Doe'}, 200, {'X-My-Custom-Header': 'Custom Value'}

All 4 comments

You should likely look into the representation functionality in the api class. Using the @api.representation() decorator, you can override the 'application/json' represenatation and inject your own headers. The example is pretty clear, but you may want to look at the vanilla flask documentation for make_response()

Yep - you could also just add them to the flask Response, like this:

resp = make_response("Hello World", 200)
resp.headers.extend({'X-Powered-By': 'AT-5000'})
return resp

Alternately if you're adding it to every request, you might consider adding the header in Nginx or Apache or similar.

Why not add the custom headers to your resource's endpoint return value?

class User(Resource):
    def get(self):
        # Some code
        return {'id': 1, 'name': 'John Doe'}, 200, {'X-My-Custom-Header': 'Custom Value'}

Any update on @linkyndy's suggestion?

Was this page helpful?
0 / 5 - 0 ratings