Gaurang Shah
Gaurang Shah

Reputation: 12910

resource optional argument for retrieving all data on Flask Restful

I am trying to understand Flask-RESTful, but I can't figure out how to provide optional arguments for resources.

I.e.:

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}


api.add_resource(TodoSimple, '/<string:todo_id>')

In above case how to create a new end point which returns all the todos, and not just one?

Taken from: https://flask-restful.readthedocs.io/en/0.3.5/quickstart.html

Upvotes: 3

Views: 2364

Answers (2)

j2logo
j2logo

Reputation: 669

I think the best approach is to have two Resources/endpoints. The first one to manage the collection (get the list of todos, add a new todo) and the second one to manage the items of the collection (update or delete item):

class TodoListResource(Resource):
    def get(self):
        return {'todos': todos}


class TodoResource(Resource):
    def get(self, todo_id):
        return {todo: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo: todos[todo_id]}


api.add_resource(TodoListResource, '/todos')
api.add_resource(TodoResource, '/todos/<string:todo_id>/')

This way is much more REST.

Upvotes: 11

willieswanjala
willieswanjala

Reputation: 678

Since you need a different route to retrieve all todos, create another class that handles multiple resources. In your case you would do something like this:

class TodoSimples(Resource):
    def get(self):
        return {'todos': todos}

api.add_resource(TodoSimples, '/todos')

Upvotes: 0

Related Questions