Introduction
Flask is a micro framework, which is used to write APIs in a very simple way. Flask is a very good example of SRP (Single Responsibility Principle). It holds the only responsibility of exposing API methods.
Why Flask?
It's a micro framework It's easy to use simple to implement, and has good flexibility. It’s already used on many high-traffic websites. LinkedIn is one of the best examples.
Usage of Flask
First, install Flask using the command: pip install flask
Below is the sample api code using flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def welcomeMessage():
return 'Welcome to flask sample api'
@app.route('/getTestMessage')
def getTestMessage():
return 'Hi this test message from flask sample api'
app.run()
Below is the code for the sample client to consume sampleApi
import requests
url = 'http://127.0.0.1:5000/'
resp = requests.get(url)
print("First response: " + resp.text)
resp = requests.get(url + 'getTestMessage')
print("Second response: " + resp.text)
Below is the output snap of sampleClient,
Above we have seen how simple it is to use and consume API which is developed using Flask.
When we talk about web frameworks, we will come across one more popular framework, Django. Django is a full-fledged web framework used for complete web application development. it has inbuilt Database migration, Admin usage, and Security protection. It helps developers to complete complex web applications without any external plugins, whereas Flask is lightweight, and used for simple web application development or static data application. For Django, I will write one more article with its usage. Both Django and Flask are good in their way. Traveling for 100kms we don’t need a flight, in same way traveling for several thousand KM a car/bike doesn’t suit us. It’s up to the developer to choose which framework suits better for our requirements.
Summary
In this article, we have seen the usage of Flask and when we can use it. I hope it will help you.