Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify JSON response of Flask-Restless

I am trying to use Flask-Restless with Ember.js which isn't going so great. It's the GET responses that are tripping me up. For instance, when I do a GET request on /api/people for example Ember.js expects:

{ 
    people: [
        { id: 1, name: "Yehuda Katz" }
    ] 
}

But Flask-Restless responds with:

{
    "total_pages": 1, 
    "objects": [
        { "id": 1, "name": "Yahuda Katz" }
    ], 
    "num_results": 1, 
    "page": 1
}

How do I change Flask-Restless's response to conform to what Ember.js would like? I have this feeling it might be in a postprocessor function, but I'm not sure how to implement it.

like image 269
Drew Larson Avatar asked Mar 15 '13 21:03

Drew Larson


People also ask

What does Jsonify do in Flask?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.

What is the difference between Flask and flask-RESTful?

Flask is a highly flexible Python web framework built with a small core and easy-to-extend philosophy. Flask-Restful is an extension of Flask that offers extension to enable writing a clean object-oriented code for fast API development.


2 Answers

Flask extensions have pretty readable source code. You can make a GET_MANY postprocessor:

def pagination_remover(results):
    return {'people': results['objects']} if 'page' in results else results

manager.create_api(
    ...,
    postprocessors={
        'GET_MANY': [pagination_remover]
    }
)

I haven't tested it, but it should work.

like image 192
Blender Avatar answered Oct 21 '22 23:10

Blender


The accepted answer was correct at the time. However the post and preprocessors work in Flask-Restless have changed. According to the documentation:

The preprocessors and postprocessors for each type of request accept different arguments, but none of them has a return value (more specifically, any returned value is ignored). Preprocessors and postprocessors modify their arguments in-place.

So now in my postprocessor I just delete any keys that I do not want. For example:

def api_post_get_many(result=None, **kw):
    for key in result.keys():
        if key != 'objects':
            del result[key]
like image 21
Drew Larson Avatar answered Oct 22 '22 01:10

Drew Larson