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>')
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=..)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With