Alon Galpe
Alon Galpe

Reputation: 65

2 GET routes to same Resource in Flask-RESTful

I am learning Flask-RESTful and I have the following task i want to do:

There are these 2 GET Routes

GET /student/id (get student details, search student by ID)
GET /student/id/grades (get student grades, search student by ID)

If i don't want to have if statement in student GET function, how can I have this implemented? I must create 2 different resources? Student and GradesList?

Thanks, Alon

Upvotes: 2

Views: 7169

Answers (3)

A. Nadjar
A. Nadjar

Reputation: 2543

Sure, You need to create 2 different resources since the second GET in the same Resource class will override the first one.

However, you can still take use of simple Flask API rather than flask_restful. You may find this thread useful:Using basic Flask vs Flask-RESTful for API development

and more importantly, this: Flask RESTful API multiple and complex endpoints

Upvotes: 2

j2logo
j2logo

Reputation: 669

Yes, you should create 2 different resources as follows:

from flask_restful import Api

api = Api(app)

class StudentResource(Resource):

    def get(self, id):
        // Your code here. This is an example
        student = Student.get(id)

class GradeListResource(Resource):

    def get(self, id):
        // Your code here. This is an example
        student = Student.get(id)
        grades = studen.grades()

api.add_resource(StudentResource, '/student/<int:id>', endpoint='student_resource')
api.add_resource(GradeListResource, '/student/<int:id>/grades', endpoint='grade_list_resource')

Upvotes: 4

paradocslover
paradocslover

Reputation: 3294

Change the order to

/student/id/grades

/student/id

The error happens because route searching happens in the order in which you list them.

For eg. say you have two routes as follows: /a/b and /a/ Let's consider two cases -

Order 1

/a/

/a/b/

Now if you search for /a/<some id> then it matches the first route and you are routed accordingly. Again, when you search for /a/b/<some id>, the prefix i.e. /a/ matches again and you are routed to the first route.

Order 2-

/a/b/

/a/

Now, if you search for /a/<some id> then it does not match the first route (as the prefix /a/b/ does not match). But the second route matches and you are routed accordingly.As an alternative, if you search for /a/b/<some id> then the first route matches. And then you are routed to the correct URL.

As a rule of thumb, remember to put the more particular case first.

Upvotes: 1

Related Questions