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

python flask mysql

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Best MySQL DigitalOcean Performance – ScaleGrid vs. DigitalOcean Managed Databases

Compare ScaleGrid MySQL vs. DigitalOcean Managed Databases - See which offers the best MySQL throughput, latency, and pricing on DigitalOcean across workloads.

Python Flask & MySQL REST API con SQLAlchemy

En este ejemplo Práctico de Python vamos a aprender a crear una REST API usando Flask y MySQL a través de un modulo llamado SQLAlchemy, el cual nos permitira interactuar con la base de datos de mysql.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Flask - Introduction to Flask Templates

This is our second tutorial in Python Flask, in this tutorial we are going to have Introduction to Flask Templates, so for this Flask looks for the template