Python Web Services: Flask

Python Web Services: Flask

I’m a firm believer of basics, so before we deep dive into something really interesting and new, I feel its mandate to make you unravel with the basic terms and technologies which we will be using in this post.

I’m a firm believer of basics, so before we deep dive into something really interesting and new, I feel its mandate to make you unravel with the basic terms and technologies which we will be using in this post.


In this Post You’ll be creating web services using Python-Flask.

Tools, Terminologies, and Technologies :

  1. Python: Python is General Purpose High Level Programming Language. General Purpose means it can be used for multiple application such as Data Science, Machine Learning, Desktop Application, Web Application, Scripts etc. High-Level Programming Language means human understandable language i.e. Human readable.
  2. Flask: Flask is a popular web framework written in Python, used for the development of web application.
  3. REST: A RESTful API is an application program interface that used uses HTTP requests to GET, PUT, POST and DELETE data.
  4. JSON: JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data or exchanging the data.

We will start by creating RESTful web services using Python and Flask.

Create a folder Student in your desktop and open terminal

$ cd Student
$ pip install Flask

Now we have Flask installed let’s create a simple web application. Inside the student create a file app.py.

Open any Text Editor and write the following code I’ll be using Atom you can use notepad or notepad++ or any other editor, inside the file app.py.

from flask import Flask
 app = Flask(_name_)
 @app.route('/')
 def hello_world():
    return 'Hello World'
 if name == 'main':
    app.run()

This is a simple Hello World program which will print Hello Nuclear Geeks to run open the terminal and type

$ cd Student
$ python app.py

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

You will get the following output. Copy and paste this to your browser and see Hello World flashing!!!

Now its time to create web services !!! 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.0.0.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.14.1 Python/3.6.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.

@app.route('/Student/', methods=['POST'])
    def add_task():
      student = {
     'id': Student[-1]['id'] + 1,
     'firstName': request.json['firstName'],
     'lastName': request.json.get('lastName', ""),
     'age': request.json.get('age',"27")
 }
 Student.append(student)
   return jsonify({'student': student}), 201

So 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.0.0.1:5000/Student/

After running following command in the terminal you will see following output.

HTTP/1.0 201 CREATED
Content-Type: application/json
Content-Length: 66
Server: Werkzeug/0.14.1 Python/3.6.1
Date: 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.0.0.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 Database

This 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….

  1. Open PyCharm, create new Python file name app.python and type the below code into your app.python file.
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    return "Hello Nuclear Geeks"
if __name__ == '__main__':
    app.run()


2. Simply we’re routing out request and displaying “Hello Nuclear Geeks”, On running the following program type http://127.0.0.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_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')
if __name__ == '__main__':
    app.run()


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

6. 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, request
from flask_mysqldb import MySQL
app = 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.connection.cursor() cur.execute("INSERT INTO MyUsers(firstName, lastName) VALUES (%s, %s)", (firstName, lastName)) mysql.connection.commit() cur.close() return 'success' return render_template('index.html')

if name == 'main': app.run()


8. 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.connection.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 connection

mysql.connection.commit()
cur.close()

9. 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.

10. 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.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python and Django Full Stack Web Developer Bootcamp

Complete Python Masterclass

The Python Bible™ | Everything You Need to Program in Python

Python at Netflix

MySQL Databases With Python Tutorial

Build Your First Python and Django Application

Exploring Python Basics (Free eBook

An A-Z of useful Python tricks

A Complete Machine Learning Project Walk-Through in Python

Learning Python: From Zero to Hero

Originally published on https://medium.com

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Python Flask for Beginners: Build a CRUD Web App with Python and Flask

In this Python Flask tutorial, you'll learn to build CRUD web applications using Python and Flask. Python and Flask can make building a CRUD app super easy.

Aprender Python, Django, Flask, Tkinter, POO, SQLite, MySQL y MÁS 🐍

Aprender Python, Django, Flask, Tkinter, POO, SQLite, MySQL y MÁS 🐍 POO, Programación Orientada a Objetos en Python. Bases de datos SQL, trabajando en conjunto con nuestros desarrollos. Tkinter, para crear aplicaciones de escritorio con interfaz gráfica. Django, el framework de desarrollo web para Python más popular y demandado por las empresas. Flask, el moderno framework para desarrollar aplicaciones web.

Building a Login System with Python Flask and MySQL for Beginners

In this tutorial, we'll be creating a complete login and registration system with Python Flask