Skip to content Skip to sidebar Skip to footer

Flask-restful - Return Custom Response Format

I have defined a custom Response format as per the Flask-RESTful documentation as follow. app = Flask(__name__) api = restful.Api(app) @api.representation('application/octet-strea

Solution 1:

What representation is used is determined by the request, the Accept header mime type.

A request of application/octet-stream will be responded to by using your binary function.

If you need a specific response type from an API method, then you'll have to use flask.make_response() to return a 'pre-baked' response object:

defget(self):
    response = flask.make_response(something)
    response.headers['content-type'] = 'application/octet-stream'return response

Solution 2:

Just return Flask response objects in your methods.

A response class allows you to provide custom headers (including the content-type): http://flask.pocoo.org/docs/api/#response-objects

Solution 3:

In addition to @Martijin Pieters' answer here - https://stackoverflow.com/a/20246014/1869562. Where you return a raw response object, Flask-Restful also allows you to set status code and headers in your return values directly.

So in your case, this should also work

classFoo(restful.Resource):defget(self):
        return something, 201, {'content-type': 'application/octet-stream'}

The default mediatype for Flask-REstful is 'application/json', so put should work as is.

Post a Comment for "Flask-restful - Return Custom Response Format"