I am aware that there are several ways of exposing your data for REST API consumption purpose on Python. However, the two methods that I used seemed to have issues with generating the key for the resulting values. Here are the two methods that I used to build my REST API:
First Method
from flask import Flask, jsonify
from flaskext.mysql import MySQL
mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_USER'] = 'user'
app.config['MYSQL_DATABASE_PASSWORD'] = 'fakepassword'
app.config['MYSQL_DATABASE_DB'] = 'router'
mysql.init_app(app)
@app.route('/api/v1/routerstatus', methods=['GET'])
def get():
cursor = mysql.connect().cursor()
cursor.execute('SELECT * FROM dm_routerstatus ORDER BY
status_update_time DESC LIMIT 100;')
rv = cursor.fetchall()
return jsonify(rv)
if __name__ == '__main__':
app.run(host='0.0.0.0')
app.run(debug=True)
Second Method
from flask import Flask, jsonify, request
from flask_restful import Resource, Api
from json import dumps
from flaskext.mysql import MySQL
*SKIPPED THE DB CREDENTIALS*
mysql = MySQL()
app = Flask(__name__)
api = Api(app)
mysql.init_app(app)
class Router(Resource):
def get(self):
conn = mysql.connect().cursor()
query = cursor.execute('SELECT * FROM dm_routerstatus ORDER BY
status_update_time DESC LIMIT 100;')
result = {'data': [i[0] for i in query.cursor.fetchall()]}
return jsonify(result)
api.add_resource(Router, '/api/v1/routerstatus')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
app.run(debug=True)
and below is an example of the request results of which is missing the key names (column name).
How do I get the key names without typing every single column titles found in the database? Thanks in advance for the responses.
