Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET with and without parameter in flask-restful

The following strikes me as inelegant but it works. Is there a way to have flask-restful handle the two standard flavors of get (i.e. get everything and get one item) using the same resource class?

Thanks.

from flask_restful import Resource
# ...

class People(Resource):
    def get(self):
        return [{'name': 'John Doe'}, {'name': 'Mary Canary'}]

class Person(Resource):
    def get(self, id):
        return {'name': 'John Doe'}
# ...

api.add_resource(People, '/api/people')
api.add_resource(Person,  '/api/people/<string:id>')
like image 694
John Lockwood Avatar asked Sep 06 '15 02:09

John Lockwood


1 Answers

I think this is what you're looking for:

from flask_restful import Resource
# ...


class People(Resource):

    def get(self, id=None):
        if not id:
            return {'name': 'John Doe'}
        return [{'name': 'John Doe'}, {'name': 'Mary Canary'}]


api.add_resource(People, '/api/people', '/api/people/<id>')

You can put restrictions on the id buy adding it as an argument to the request parser:

parser.add_argument('id', location='view_args', type=..)
like image 184
kardaj Avatar answered Sep 20 '22 12:09

kardaj