I found many alternative and mixed methods while I was working on how to build a REST API to read my database table in MySQL. For my first step, I had only need to make basic API GET requests and I achieved to take request log. Here we will see Python REST API Read example using Flask and MySQL.
Have Python installed in Windows
Python version and Packages
I am using Python 3.7 version (I used Spyder IDE)
We are looking for our directory folder to make sure that our file is located in the directory that we want to work from.
print(“Current Working Directory “ , os.getcwd())
If we want to create a new folder and transfer our directory to this folder we are going to code:
os.chdir(“your new path”)
Install Flask and JSONify by using Pip. Pip is a package installer for Python and it comes with Python. Flask is a microframework for Python and JSONify is a minimal HTML-form to JSON to HTML-form converting plugin for JQuery. Open a Terminal like Anaconda Prompt to make Flask installed.
pip install flask-restful
Create a “.py” script under your directory folder where we import the flask module. Here we are coding flask instance.
from flask import Flask
app = Flask(__name__)
Create another “.py” script to set up the MySQL database configurations for connecting to the database. We import app module because we need to connect to database by using flask module. You should write your database info into the quotation marks below.
from app import app
from flaskext.mysql import MySQL
mysql = MySQL()
# MySQL configurations
app.config[‘MYSQL_DATABASE_USER’] = ‘’
app.config[‘MYSQL_DATABASE_PASSWORD’] = ‘’
app.config[‘MYSQL_DATABASE_DB’] = ‘’
app.config[‘MYSQL_DATABASE_HOST’] = ‘’
Create your last “.py” script under your directory folder. This script is the perfect instance of Python REST API CRUD Example using Flask and MySQL. In this example the only function is to Read the selected table in JSON format.
Be sure that your MySQL Workbench is open and connected.
You are going to check all your codes and start from Step #4 script and run your three scripts one by one. The output will be like below:
- Serving Flask app “app” (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
We are going to use any API Test tools to test our API applications. In this example RESTLET Client is our tool and you can reach from this link. https://restlet.com/modules/client/. I recommend the chrome extension version of this tool. You are going to enter the above localhost path with the function name “user” in this method.
If you see the 200 OK response and the JSON format data selected from the database under the BODY column, you will be accomplished in the very beginning of the Building of RESTFUL API.