1

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?

How do I get the key names without typing every single column titles found in the database? Thanks in advance for the responses.

1 Answer 1

1

Use a DictCursor (MySQLdb.cursors.DictCursor)

Sign up to request clarification or add additional context in comments.

1 Comment

Alright. Now I understand. Thanks. I just need to add dict in the query line. Let's set the second method for example: res = [dict((conn.description[i][0], value) for i, value in enumerate(row)) for row in conn.fetchall()]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.