I'm trying to return this list in flask. Teacher is a class and returns objects.
@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
teachers = []
for teacher in Teacher.objects:
teachers.append(teacher)
return teachers
This code returns the typical error of
TypeError: 'list' object is not callable The view function did not return a valid response.
I'm going crazy and I don't know what's going on. Does anyone know?
Thank you!!
EDIT:
I've already worked it out. The problem was not how to return the list, the problem was the serialization in JSON of the objects.
@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
teachers = []
for teacher in Teacher.objects:
teacherJson = teacher.to_json()
teacherData = json.loads(teacherJson)
teachers.append(teacherData)
return jsonify({'teachers': teachers})
Thanks for your help.
You can't return a list from a view: HTTP is for moving text around. If you're trying to use it as an endpoint for an API, then you can encode it in some way like JSON and parse that in the code that uses the API.
jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.
You can't return a list directly from flask view.please try to jsonify
from flask import jsonify
@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
teachers = []
for teacher in Teacher.objects:
teachers.append(teacher)
return jsonify(teachers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With