22

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.

Ayrx
  • 2,092
  • 5
  • 26
  • 34

3 Answers3

26

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Alex
  • 1,210
  • 8
  • 15
  • 1
    How would this work within the Resource class? Some code snippets will be helpful. – Ayrx Nov 27 '13 at 13:53
  • 1
    I'm looking at https://github.com/twilio/flask-restful/blob/master/flask_restful/__init__.py line 475 dispatch_request and it's possible to return flask Response object – Alex Nov 27 '13 at 14:58
  • I stand corrected. This does not explain how to use the custom representations, however. – Martijn Pieters Nov 27 '13 at 14:59
1

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

class Foo(restful.Resource):

    def get(self):
        return something, 201, {'content-type': 'application/octet-stream'}

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

Kudehinbu Oluwaponle
  • 1,045
  • 11
  • 11