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