Python - Flask

Shubham Saket
Apr 25 · 5 min read

Host your own API.

Flask is a web application framework. It is sometimes also called a micro framework as it keeps API core very simple.

This post will mainly focus on the application of Flask framework. Here is the link to Flask documentation if you wish to know more.

I will be using Postman to test the APIs. To know more about Postman click here.

  1. Let us start with an “hello world” example of a function in Python:
def hello_world():
return "Hello World"

We can access the function over a network using Flask:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
return "Hello World"

if __name__ == '__main__':
app.run()
  • In the above code we create a Flask object “app”. “__name__” is an input required by Flask which is just the name of python script in which the code is written. Example: if the name of the script is “app.py” then we can also initiate the Flask object as:
    app = Flask(“app”)
  • @app.route(‘/’) is decorator which binds the function to the server URL. Parameter “/” states that path to the function on the server i.e. at root. The “methods” parameter can restrict request to a particular method. We can do that by changing the code from @app.route(‘/’) to @app.route(‘/’,methods=[“GET”, “POST”])
  • app.run() this method runs the application on a local development server. It has “host” and “port” as its parameter which defaults to “127.0.0.1” and 5000 respectively.
  • If we run this python script we will be able access this function via URL “http://127.0.0.1:5000/” which is a default in Flask. (If one wishes to expose the function to external network “host” should be changed to “0.0.0.0” which reflects the machine IP over the external network)

We can see that the Flask server is up and running. Now let us try to ping the server from POSTMAN.

We can see that after pinging to the server URL we got “Hello World” as our response. This implies that our API is working well.

2. Let us examine another use-case where if for example a user pings the URL “http://127.0.0.1:5000/Chuck” it should return “Hello Chuck”. The URL should only accept the “POST” method and function should be externally exposed over the network.

from flask import Flask
app = Flask("app")

@app.route('/<name>',methods=['POST'])
def hello_name(name):
return "Hello {}".format(name)

if __name__ == '__main__':
app.run(host="0.0.0.0",port=5586)
  • We can see that ‘GET’ method is blocked for this API as we have specifically mentioned “POST” methods as only valid method.
  • By changing the method to “POST” in POSTMAN we are able to access the function which returns a response as expected.
  • This code is a classic example of dynamic URLs. “<name>” in the @app.route(“/<name>”) indicates that string in place of “<name>” becomes a value for parameter “name” of “hello_name” function.

3. We will now create an API to upload a image and get resized image in return.

from flask import Flask,request,send_file
import numpy as np
import cv2
app = Flask("app")

@app.route('/',methods=['GET','POST'])
def resize():
if 'image' in request.files:
img = request.files['image']
img = img.read()
img = np.fromstring(img,np.uint16)
img = cv2.imdecode(img,cv2.IMREAD_COLOR)
img = cv2.resize(img,(200,200))
cv2.imwrite('tmp.jpg',img)
return send_file('tmp.jpg')
else:
return {'error':'image not found'}


if __name__ == '__main__':
app.run(host="0.0.0.0",port=5586)
  • To accomplish this task we import “request”, “send_file” object from flask module. ‘request’ object helps us to read the input file and “send_file” object is used to return a file as response.
  • When we receive a file from a request to server it is of type: “<FileStorage: ‘example.JPG’ (‘image/jpeg’)>
  • .read()” method changes the file type to bytes: “b’\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00x\x00x\x00\x00\xff\xe1\x10\xf4Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x04\x01;\x00\x02\x00\x00\x00\x0e\x00\x00\x08J\x87i\x00\x04\x00'”
  • np.fromstring()” changes the bytes to one dimensional numpy array: “[55551 57599 4096 17994 17993 256 257 30720 30720 0 57855 62480, 30789 26217 0 19789 10752 0 2048 1024 15105 512 0 3584, 0 18952 27015 1024 0 256 0 22536 40348 256 0 7168, 0 53264 7402 1792 0 3080 0 15872 0 0 59932 0, 2048 0 0 0 0 0 0 0 0 0 0 0, 0 0 0 0 0 0 0 0 0 0 0 0, 0 0 0 0 0 0 0 0 0 0 0 0, 0 0 0 0 0 0 0 0 0 0 0 0, 0 0 0 0]
  • cv2.imdecode()” (opencv) decodes the original image from one dimensional numpy array.
  • When we have an image into its proper format we can apply “resize” function or any other image function on it.
  • After resizing the image we are saving it as a temporary file and then sending the file as APIs response.

Our input image:

Output response:

4. Let us explore another use case where we have an input csv file and output should be its dimension.

from flask import Flask,request,send_file
import pandas as pd
app = Flask("app")

@app.route('/shape',methods=['GET','POST'])
def shape():
if 'csv' in request.files:
csv = request.files['csv']
csv = pd.read_csv(csv)
return "shape: {}".format(csv.shape)
else:
return {'error':'csv not found'}


if __name__ == '__main__':
app.run(host="0.0.0.0",port=5586)
  • “read_csv” method of pandas library manages the conversion of csv file to dataframe from “FileStorage” type.
  • I added “shape” in the decorator path so now to send a request to this API the URL should be “http://0.0.0.0:5586/shape”.

I hope this post helped you in learning basic concept of Flask web application framework.

That’s all folks.

Geek Culture

Proud to geek out. Follow to join our +500K monthly readers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store