John Lockwood
John Lockwood

Reputation: 3875

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>')

Upvotes: 9

Views: 7157

Answers (2)

kardaj
kardaj

Reputation: 1935

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=..)

Upvotes: 12

siegerts
siegerts

Reputation: 471

Yeah, check out the argument parsing documentation. If needed, this will give you the flexibility to create some logic around the arguments received with the request.

from flask_restful import Api, Resource, reqparse
# ...

api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('id')

class People(Resource):
def get(self):
    data = parser.parse_args()
    if not data['id']:
        return [{'name': 'John Doe'}, {'name': 'Mary Canary'}]
    else:
        # data lookup using id
        # for example using SQLAlchemy...
        # person = Person.query.filter_by(id = data['id']).first_or_404()
        return {'id': data['id'], 'name': 'John Doe'}

api.add_resource(People, '/api/people')

Then try with:

  • localhost:/api/people
  • localhost:/api/people?id=1

Upvotes: 0

Related Questions