Search code examples
pythonjsonflaskflask-restful

Display all the names of students from certain faculties using flask_restful


I have a json data named data.py

students= [
{'name': 'Andika',
 'dept': 'FTTI',
 'gpa': 3.2,},
{'name': 'Budi',
 'dept': 'FTTI',
 'gpa': 3.7,},
{'name': 'Iman',
 'dept': 'FTTI',
 'gpa': 3.4,}
{'name': 'Mia',
 'dept': 'FES',
 'gpa': 3.9,},
{'name': 'Fajar',
 'dept': 'FES',
 'gpa': 2.9,}
]

I try to display all the names of students from certain faculties (dept) Using Flask_restful API. If not found, must return the JSON object {'student names': 'None'}, 404

And here my code named student.py

from flask import Flask
from flask_restful import Resource, Api
from data import students

app = Flask(__name__)
api = Api(app)
class StudentDept(Resource):
    def get(self, dept):
        names=[]
        for student in students:
            names.append(student['name'])
            if student['dept']==dept:
                return {'studentnames':names}
        return {'studentnames':'None'}, 404

api.add_resource(StudentDept, '/student/name/<string:dept>')
app.run(port=5000, debug=True)

But the result just appear 1 name in http://127.0.0.1:5000/student/name/FTTI

The result must like this in http://127.0.0.1:5000/student/name/FTTI

how should the correct code?


Solution

  • It's because your code works like this: when you see a person with the dept that you want: return names (so it only returns the first one) what you need to do is to wait until the loop is over so and then return the people who have this dept

    class StudentDept(Resource):
        def get(self, dept):
            names=[]
            right_dept = []
            for student in students:
                names.append(student['name'])
                if student['dept']==dept:
                    right_dept.append(student['name'])
            if len(right_dept) == 0:
                return {'studentnames':'None'}, 404
            else:
              return {'studentnames':right_dept}
    

    If you would've used a debugger you would have seen the problem so I suggest using it, for next time whenever you encounter such problems.