Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 382
Alon Galpe Avatar asked Jan 21 '26 10:01

Alon Galpe


1 Answers

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')
like image 103
j2logo Avatar answered Jan 22 '26 23:01

j2logo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!