Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 435
Gaurang Shah Avatar asked Jan 27 '26 15:01

Gaurang Shah


1 Answers

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.

like image 85
j2logo Avatar answered Jan 30 '26 06:01

j2logo