2

I have implemented a flask-restful get handler that returns a number of records in an array. I want to set the header "x-total-count" to the number of records returned. I was able to add a header for every request using @api.representation but I am looking for a way to add the header in my get handler as it is specific to that particular endpoint.

@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = make_response(json.dumps(data), code)
    headers = dict(headers) if headers else {}
    headers["X-Total-Count"] = str(len(data))
    resp.headers.extend(headers)
    return resp

class Customers(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, required=True)
        parser.add_argument('per-page', type=int, required=True)

        args = parser.parse_args()

        page_num = args['page']
        per_page = args['per-page']

        cxn = sqlite3.connect('chinook.db')
        sql = 'SELECT CustomerId, FirstName, LastName, Address, City, PostalCode, State FROM customers ' + \
              'WHERE CustomerId not in (SELECT CustomerId from customers ' + \
              'ORDER BY LastName ASC LIMIT ' + str((page_num-1) * per_page) + ')' + \
              'ORDER BY LastName ASC LIMIT ' + str(per_page)

        data = []
        for row in cxn.execute(sql):
            data.append({
                "id": row[0], "first-name": row[1], "last-name": row[2], "address": row[3],
                "city": row[4], "state": row[5], "postal-code": row[6] })

        cxn.close()
        return data
Shane
  • 2,271
  • 3
  • 27
  • 55
  • Please refer to [this answer](https://stackoverflow.com/questions/25860304/how-do-i-set-response-headers-in-flask) – Himanshu Bansal Nov 14 '17 at 04:54
  • @Himanshu - I am using flask-restful any my handler which returns a python data structure not a Response object so am not sure how apply make response in this case. I have added my code to make it more clear. – Shane Nov 14 '17 at 05:09
  • try this https://flask-restful.readthedocs.io/en/latest/extending.html#response-formats – Himanshu Bansal Nov 14 '17 at 05:18
  • @Himanshu - I was able to add headers in a "gloabal" handler but I want it to be request specific. Have edited my question accordingly. – Shane Nov 16 '17 at 05:24

0 Answers0