Search code examples
pythonmongodbflaskflask-restfulflask-restplus

Response class in Flask-RESTplus


What is the proper way to handle response classes in Flask-RESTplus? I am experimenting with a simple GET request seen below:

i_throughput = api.model('Throughput', {
    'date': fields.String,
    'value': fields.String    
})

i_server = api.model('Server', {
    'sessionId': fields.String,
    'throughput': fields.Nested(i_throughput)
})

@api.route('/servers')
class Server(Resource):
    @api.marshal_with(i_server)
    def get(self):
        servers = mongo.db.servers.find()
        data = []
        for x in servers:
            data.append(x)

        return data

I want to return my data in as part of a response object that looks like this:

{
  status: // some boolean value
  message: // some custom response message
  error: // if there is an error store it here
  trace: // if there is some stack trace dump throw it in here
  data: // what was retrieved from DB
}

I am new to Python in general and new to Flask/Flask-RESTplus. There is a lot of tutorials out there and information. One of my biggest problems is that I'm not sure what to exactly search for to get the information I need. Also how does this work with marshalling? If anyone can post good documentation or examples of excellent API's, it would be greatly appreciated.


Solution

  • https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class

    from flask import Flask, Response, jsonify
    
    app = Flask(__name__)
    
    class CustomResponse(Response):
        @classmethod
        def force_type(cls, rv, environ=None):
            if isinstance(rv, dict):
                rv = jsonify(rv)
            return super(MyResponse, cls).force_type(rv, environ)
    
    app.response_class = CustomResponse
    
    @app.route('/hello', methods=['GET', 'POST'])
    def hello():
        return {'status': 200, 'message': 'custom_message', 
                'error': 'error_message', 'trace': 'trace_message', 
                'data': 'input_data'}
    

    result

    import requests
    response = requests.get('http://localhost:5000/hello')
    print(response.text)
    
    {
      "data": "input_data",
      "error": "error_message",
      "message": "custom_message",
      "status": 200,
      "trace": "trace_message"
    }