Python Web Services: Flask

This tutorial will not have database interaction with Python, I’ll be writing one soon.

Here we will be using our own memory there we will be storing our JSON data.

Write the following code inside the app.

py file.

from flask import Flask, jsonify app = Flask(name) Student = [ { 'id': 1, 'firstName': 'Aditya', 'lastName': 'Malviya', 'age': '24' }, { 'id': 2, 'firstName': 'Aman', 'lastName': 'Mehta', 'age': '25' }, { 'id': 3, 'firstName': 'Nuclear', 'lastName': 'Geeks', 'age': '26' } ] @app.

route('/Student/', methods=['GET']) def get_Student(): return jsonify({'tasks': Student}) if name == 'main': app.

run()So we’ve create an array of dictionary in our memory, Here we have get_Student() function which will fetch all the Students from our memory.

This is the example of GET Request.

To run the above copy and paste this to your browser “http://127.



1:5000/Student/”  and hit Enter you’ll get the list of students or enter the following command in the terminal and hit Enter.

curl -i http://localhost:5000/Student/ HTTP/1.

0 200 OK Content-Type: application/json Content-Length: 199 Server: Werkzeug/0.


1 Python/3.


1 Date: Fri, 26 Apr 2019 16:23:13 GMT {"tasks":[{"age":"24","firstName":"Aditya","lastName":"Malviya","id":1},{"age":"25","firstName":"Aman","lastName":"Mehta","id":2},{"age":"26","firstName":"Nuclear","lastName":"Geeks","id":3}]}Next is out POST Request, Here we will be posting one more Student data into our existing data.

The request.

json will have the request data, but only if it came marked as JSON.

We will append the new task in our Student array, and then respond to the client with the added task.

Write the following code inside the app.

py file.


route('/Student/', methods=['POST']) def add_task(): student = { 'id': Student[-1]['id'] + 1, 'firstName': request.

json['firstName'], 'lastName': request.


get('lastName', ""), 'age': request.


get('age',"27") } Student.

append(student) return jsonify({'student': student}), 201So here we’ve created a new function for adding the Student data in our array, we will be taking the same from the user and appending to our data.

To run the following code copy paste into your terminal and hit Enter.

curl -i -H "Content-Type: application/json" -X POST -d '{"firstName":"SAM"}' http://127.



1:5000/Student/After running following command in the terminal you will see following output.


0 201 CREATEDContent-Type: application/jsonContent-Length: 66Server: Werkzeug/0.


1 Python/3.


1Date: Sat, 26 Apr 2019 05:19:12 GMT{"student":{"age":"27","firstName":"SAM","lastName":"","id":4}}And you’ve successfully posted your data!!!.Simple isn’t it?… You can fetch all the student data by our first command.

Copy and paste this to your browser “http://127.



1:5000/Student/”  and hit Enter you’ll get the list of students or enter the following command in the terminal and hit Enter.

curl -i http://localhost:5000/Student/Connect Flask to MYSQL DatabaseThis tutorial is completely made for beginner, So the prerequisite of this tutorial is going to be the minimum only thing which I will personally recommend it to have a high level overview of Python web services using Flask and have minimum understanding of SQL and Database set up.

To get started you’ll be needing any IDE I’ll be using PyCharm, MySQL DB and that’s it!!!.This tutorial, unlike my earlier posts, will be steps depicting what and how to do….

Open PyCharm, create new Python file name app.

python and type the below code into your app.

python file.

from flask import Flaskapp = Flask(__name__)@app.

route('/', methods=['GET', 'POST'])def index(): return "Hello Nuclear Geeks"if __name__ == '__main__': app.


Simply we’re routing out request and displaying “Hello Nuclear Geeks”, On running the following program type http://127.



1:5000/ on your browser to see the output!!.“Hello World”3.

Now you need to create a simple HTML page with two text field First Name, Last Name and submit button.

To do this create a folder named Templates inside it create a file index.

html and copy the below code.

<HTML><BODY bgcolor="cyan"><form method="POST" action=""> <center> <H1>Enter your details </H1> <br> First Name <input type = "text" name= "fname" /> <br> Last Name <input type = "text" name = "lname" /> <br> <input type = "submit"> </center></form></BODY></HTML>4.

Modify our app.

python file and add the below code in it.

from flask import Flask, render_templateapp = Flask(__name__)@app.

route('/', methods=['GET', 'POST'])def index(): return render_template('index.

html')if __name__ == '__main__': app.


Upon running the above code you must get the page as below.


Now we’ve developed our form, the next step is database connection.

To create a table use the below query:CREATE TABLE MyUsers ( firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL);7.

The above query will create a table in the Database with name MyUsers, now copy the following code and paste in app.

python file.

from flask import Flask, render_template, requestfrom flask_mysqldb import MySQLapp = Flask(__name__)app.

config['MYSQL_HOST'] = 'localhost'app.

config['MYSQL_USER'] = 'root'app.

config['MYSQL_PASSWORD'] = 'root'app.

config['MYSQL_DB'] = 'MyDB'mysql = MySQL(app)@app.

route('/', methods=['GET', 'POST'])def index(): if request.

method == "POST": details = request.

form firstName = details['fname'] lastName = details['lname'] cur = mysql.


cursor() cur.

execute("INSERT INTO MyUsers(firstName, lastName) VALUES (%s, %s)", (firstName, lastName)) mysql.


commit() cur.

close() return 'success' return render_template('index.

html')if __name__ == '__main__': app.


Pretty easy till now!!!app.

config[‘MYSQL_HOST’] = ‘localhost’app.

config[‘MYSQL_USER’] = ‘root’app.

config[‘MYSQL_PASSWORD’] = ‘root’app.

config[‘MYSQL_DB’] = ‘MyDB’These lines represent the db configuration required for our Flask, the next line ‘mysql = MySQL(app)’ creates an instance which will provide us the access.

The lines ‘firstName = details[‘fname’]’ and ‘lastName = details[‘lname’]’ fetches the entered value in the HTML form.

Establishment of connection is done by ‘cur = mysql.


cursor()’ and execution of query by ‘cur.

execute(“INSERT INTO MyUsers(firstName, lastName) VALUES (%s, %s)”, (firstName, lastName))’Once the execution is done you can commit and close the connectionmysql.




Heavy Breathing!!!.we are all set to run….

Run the program enter the First Name = “Aditya” and Last Name= “Malviya” and tap on submit.

You will see success being returned on the screen.


Open the database and run the following query…SELECT * FROM MyUsers;11.

You will be seeing the following output….

> mysql> select * from MyUsers;+———–+———-+| firstname | lastname |+———–+———-+| Aditya | Malviya |+———–+———-+Easy !!!.This was all about MySQL connection using Flask.


. More details

Leave a Reply