Modify JSON response of Flask-Restless
Asked Answered
A

2

8

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.

Avernus answered 15/3, 2013 at 21:0 Comment(1)
Sigh... I tried asking the inverse question and somebody just said I should change how Flask-Restless responds. TBH I am much more comfortable in Python so doing it this way does appeal to me.Avernus
A
4

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]
Avernus answered 3/12, 2013 at 21:21 Comment(0)
T
10

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.

Twayblade answered 15/3, 2013 at 21:46 Comment(3)
I am really embarrassed it was that simple, but thank you so much.Avernus
I tested this and it did not.Benis
@datasmid: That's not helpful at all.Twayblade
A
4

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]
Avernus answered 3/12, 2013 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.