Q:

Flask REST API responding with a JSONArray

I have created a simple REST API using Flask for an Android application. I'm having trouble implementing the GET method. It is supposed to return all the records in the form of a JSONArray. The response would look something like his
{
    "tasks": [{
               "task" : "Do it",
               "timestamp": 1433510946152
              },{..}
             ],
    "success": 1
}

My Task model looks like this
class Task(db.Model):   
    id = db.Column(db.Integer, primary_key=True)
    task= db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.Integer, nullable=False)

    @staticmethod
    def newest():
        return Task.query.order_by(desc(Task.timestamp))

    def to_json(self):
        return dict(id=self.id,
                    task= self.task,
                    timestamp = self.timestamp)

The to_json() method converts the result into JSON. I just don't know how to use it appropriately. How would I put all the records inside of an JSONArray? Here is my method that gets all the tasks. I'm using Flask paginate too, so tasks is a pagination object.
def get_tasks():    

    page = request.args.get('page')
    if page is not None:
        try:
            page = int(request.args.get('page'))
        except:
            return jsonify({'result': 'Invalid parameter'})
    else:
        page = 1
    tasks= models.Task.newest().paginate(page, 7, True)

    #How do I return the tasks in an appropriate format?

Any help would be appreciated. Thanks.

A:

Simply loop over your tasks, convert them into json using your to_json and store them inside of an array. For example:
def get_tasks():    

    page = request.args.get('page')
    if page is not None:
        try:
            page = int(request.args.get('page'))
        except:
            return jsonify({'result': 'Invalid parameter'})
    else:
        page = 1
    tasks= models.Task.newest().paginate(page, 7, True)
    # This list will hold all your tasks in JSON format
    jsontasks = []
    # Since tasks is a pagination object, you should use tasks.items
    for task in tasks.items:
        jsontasks.append(task.to_json())
    #How do I return the tasks in an appropriate format? Like this..
    return jsonify({'tasks': jsontasks, 'success': 1})

