/ Python

Basic REST API Using Flask and MySQL - GET

The example below returns not only the results as JSON, but also conveniently includes the database table's column names in the result. The example assumes Python and MySQL are already installed and configured.

1. Install PIP Dependencies
pip install Flask flask-mysql
2. Basic API


from flask import Flask, jsonify
from flaskext.mysql import MySQL

app = Flask(__name__)
mysql = MySQL()

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'my_user'
app.config['MYSQL_DATABASE_PASSWORD'] = 'my_password'
app.config['MYSQL_DATABASE_DB'] = 'my_database'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'


def get():
    cur = mysql.connect().cursor()
    cur.execute('''select * from my_database.my_table''')
    r = [dict((cur.description[i][0], value)
              for i, value in enumerate(row)) for row in cur.fetchall()]
    return jsonify({'myCollection' : r})

if __name__ == '__main__':
3. Execute App and Review Results
cd directory_where_file_above_resides
python my_app.py

Default port for Flask is 5000. Open your browser and paste in the URL bar to call your cool new API.