0

I'm following the testdriven.io course.

I've found that by adding the GET All users route does not work as the request expects a userid.

In the users.py file I have:

    def get(self):  
        return User.query.all(), 200

and

def get(self, user_id):  
     ...  

and then have

api.add_resource(UsersList, '/users')  
api.add_resource(UsersList, '/users/<int:user_id>')  

It seems that by including the '/users/int:user_id' route that the '/users' route fails with:

src/tests/test_users.py::test_all_users - TypeError: get() missing 1 required positional argument: 'user_id'

If I comment out the api.add_resource(UsersList, '/users/int:user_id') route then the all users route works fine.

Is there a way to allow both (all users and user by userid) routes to work?

Am I able to do similar in other frameworks such as Lumen (PHP so possibly missing something obvious.

Thanks

Jas

davidism
  • 121,510
  • 29
  • 395
  • 339
jason
  • 64
  • 6
  • I guess this could work: @api.marshal_with(user). def get(self, user_id=None): if user_id is None: return User.query.all(), 200 user= User.query.filter_by(id=user_id).first() if not user: api.abort(404, f"User {user_id} does not exist"). return user, 200 – jason Jan 03 '22 at 22:38

1 Answers1

0

I think this might be the answer but I was hoping to be able to add multiple GET functions to separate out the code.

This:

Handle both the /users and users/id routes in the same method. Is it possible to have both GET functions and separate the logic/code.

    @api.marshal_with(user)
    def get(self, user_id=None):
        if user_id is None:
            return User.query.all(), 200

        user= User.query.filter_by(id=user_id).first()
        if not user:
            api.abort(404, f"User {user_id} does not exist")

        return user, 200
jason
  • 64
  • 6