Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-RESTful - Return custom Response format

Tags:

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-stream') def binary(data, code, headers=None):     resp = api.make_response(data, code)     resp.headers.extend(headers or {})     return resp  api.add_resource(Foo, '/foo') 

I have the following Resource class.

class Foo(restful.Resource):      def get(self):         return something      def put(self, fname):         return something 

I want the get() function to return the application/octet-stream type and the put() function to return the default application/json.

How do I go about doing this? The documentation isn't very clear on this point.

like image 365
Ayrx Avatar asked Nov 27 '13 13:11

Ayrx


People also ask

What is Flask_restful?

Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs. It is a lightweight abstraction that works with your existing ORM/libraries. Flask-RESTful encourages best practices with minimal setup.


1 Answers

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:

def get(self):     response = flask.make_response(something)     response.headers['content-type'] = 'application/octet-stream'     return response 
like image 82
Martijn Pieters Avatar answered Sep 21 '22 14:09

Martijn Pieters