How to Create REST API Using Python Flask.

How to Create REST API Using Python Flask.

Architectural Design Pattern of developing API is called REST, which is the acronym for REpresentational State Transfer. That means, when the client is requesting the server, it will transfer the representation of the state of the response. One of the advantages of REST API to develop the “code on-demand”. REST API can be developed using any programming language but with Python Flask, it is very easy and lightweight. So, let’s see how REST API can be easily developed using Python Flask. In this article, we will discuss How to Create REST API Using Python Flask.

Installing Flask Application.

As discussed, Flask is the light-weight python framework. So, Flask can be easily installed using PIP. If you are not having PIP, then install PIP first. Before that, make sure you have python installed or not. Then, Install PIP. By using PIP, we can install the python flask framework.

Installing on windows.

  • Step 1: Install PIP by downloading get-pip.py.
  • Step 2: From Command prompt, change the directory of the downloaded file
  • Step 3: Run Command: python get-pip.py
  • Step 4: Then, run command: pip install flask-restful

Installing on Ubuntu.

  • Step 1: Update and Upgrade apt-get.
sudo apt-get upgrade
sudo apt-get update
  • Step 2: Install PIP
sudo apt-get install python-pip    #python 2
sudo apt-get install python3-pip   #python 3
  • Step 3: Then, run command: pip install flask-restful

Installing on CentOS

  • Step 1: Install the YUM package.
sudo yum install epel-release
  • Step 2: Install PIP
sudo yum install python-pip         #python 2
sudo yum install python3-pip       #python 3
  • Step 3: Then, run command: pip install flask-restful
FutureLearn Limited

Developing Restful API with CRUD Operations.

CRUD Operations are mostly used in SQL where Create, Read, Update and Delete functions are used. As discussed, RESTFul (REpresentational State Transfer) means when the client is requesting server, the Server will transfer the representation of the state of the response. So, CRUD operation will take place mostly to represent the state of the response. For example, When the Client is requesting for creating the record over HTTP connection, The Server will get the input and create the record and representation of the response will be transferred to the client as acknowledgment.

So, in this tutorial, we will discuss, How to Create REST API Using Python Flask Quickly with CRUD operations.

app.py

As the beginning of the development, create a file called app.py and import required flask modules as followed

from flask import Flask
from flask_restful import reqparse, Api, Resource, 

app = Flask(__name__)

So, By Adding the above lines, we have added Flask, app, MySQL, API, Resource and reqparse modules. Then, we are creating an app using the python flask module. “__name__” is the variable that evaluates the name of the current module.

dbconfig.py

As always, Let’s take books as an example of the data in this tutorial.

And assume the data is in MySQL database so let’s plan for the dbconfig.py file to configure the DB connectivity.

from app import app
from flaskext.mysql import MySQL

MySql = MySQL()
app.config['DATABASE_USER'] = 'root'
app.config['DATABASE_PASSWORD'] = 'root'
app.config['DATABASE_DB'] = 'digitalvarys'
app.config['DATABASE_HOST'] = 'localhost'
MySql.init_app(app)

main.py

Now, for the logic part, let’s create main.py.

import pymysql
from dbconfig importMySql
from app import app
from flask import Flask, jsonify, request

# CRUD Operation - CREATE 
@app.route('/add', methods=['POST'])
def add_book():
	try:
		json = request.json
		Book_name = json['book_name']
		Author_name = json['author_name']
		Publisher_name = json['publisher_name']
		if Book_name and Author_name and Publisher_name and request.method == 'POST':
			SQL_Query = "INSERT INTO books(Book_name, Author_name, Publisher_name) VALUES(%s, %s, %s)"
			data = (Book_name, Author_name, Publisher_name,)
			connection =MySql.connect()
			Pointer = connection.cursor()
			Pointer.execute(SQL_Query, data)
			connection.commit()
			response = jsonify('Book added!')
			response.status_code = 200
			return response
		else:
			return not_found()
	except Exception as e:
		print(e)
	finally:
		Pointer.close() 
		connection.close()
		
#CRUD Operation - READ			
@app.route('/book/<int:id>')
def book(id):
	try:
		connection =MySql.connect()
		Pointer = connection.cursor(pymysql.cursors.DictCursor)
		Pointer.execute("SELECT * FROM books WHERE book_id=%s", id)
		record = Pointer.fetchone()
		response = jsonify(record)
		response.status_code = 200
		return response
	except Exception as e:
		print(e)
	finally:
		Pointer.close() 
		connection.close()

#CRUD Operation - UPDATE	
@app.route('/update', methods=['POST'])
def update_book():
	try:
		json = request.json
		id = json['id']
		Book_name = json['Book_name']
		Author_name = json['Author_name']
		Publisher_name = json['Publisher_name']		
		if Book_name and Author_name and Publisher_name and id and request.method == 'POST':
			SQL_Query = "UPDATE books SET Book_name=%s, Author_name=%s, Publisher_name=%s WHERE book_id=%s"
			data = (Book_name, Author_name, Publisher_name, id,)
			connection =MySql.connect()
			Pointer = connection.cursor()
			Pointer.execute(sql, data)
			connection.commit()
			response = jsonify('Book updated!')
			response.status_code = 200
			return response
		else:
			return not_found()
	except Exception as e:
		print(e)
	finally:
		Pointer.close() 
		connection.close()

#CRUD Operation - DELETE		
@app.route('/delete/<int:id>')
def delete_book(id):
	try:
		connection =MySql.connect()
		Pointer = connection.cursor()
		Pointer.execute("DELETE FROM books WHERE book_id=%s", (id,))
		connection.commit()
		response = jsonify('book deleted!')
		response.status_code = 200
		return response
	except Exception as e:
		print(e)
	finally:
		Pointer.close() 
		connection.close()
		
if __name__ == "__main__":
    app.run()

In this we have covered all the CRUD operations. Say:

  • Method add_book will do the CREATE operation with creating a record in books table with the HTTP POST method.
  • Then, READ operation is done with the method read with HTTP GET Method.
  • UPDATE method is taken care of by the update_book method with HTTP PUT Method.
  • Finally, the delete_book is for DELETE Operation with the HTTP DELETE method.

Note: Since this is a very simple tutorial to understand the RESTful API and CRUD operations, we have used flask as an example as it is very lightweight. As part of the framework, flask supports handling database easily. But in this tutorial, create a table named books with three fields Book_name, Author_name, and Publisher_name)

Download the Source code from GitHub Repository.

Now, Run the application by passing the below command.

python main.py

This will open the flask application in port 5000 by default. If you want to change it to port 8000 (for example), mention the desired port in app.run(port=8000) in main.py. By accessing http://localhost:5000, you can connect the REST APIs.

Install Postman or any other REST client to access and test the APIs.

To GET the specific of the book (For example book ID 1), run http://localhost:5000/book/1 as GET request in postman. You will get the output as

{
    "id": 1,
    "Book_name": "test book name",
    "Author_name": "test auther name",
    "Publisher_name": "test publisher name",
}

Similarly, to CREAT a record, Run POST method http://localhost:5000/add in postman with the following Request body.

{
    "Book_name": "another test book name",
    "Author_name": "another test auther name",
    "Publisher_name": "another test publisher name",
}.

This will give you response “Book added”

For DELETE operation run http://localhost:5000/delete/2 in postman as GET operation.

To UPDATE the record, run http://localhost:5000/update with the Request Body

{
    "id": 1,
    "Book_name": "test book name updating",
    "Author_name": "test auther name updating",
    "Publisher_name": "test publisher name updating",
}

Then, you will get a response, as Book updated!

Conclusion

So far, we have discussed How to Create REST API Using Python Flask framework. RESTful API is not only useful for developers. Also, it is very useful for DevOps person to automate certain things like accessing different tools from one another using REST APIs. For example, if you want to automate syncing GitLab and BitBucket, we can use the REST API of both into Python flask and script such a way that it will GET Repo detail from one and UPDATE/POST in another. We will discuss Syncing GitLab and BitBucket using REST API and Flask in our upcoming article. Stay tuned and subscribe DigitalVarys for more articles and study materials on DevOpsAgileDevSecOps and App Development.   

Leave a Reply