Hey fellas! Welcome to the new series on Flask for dummies.
Introduction
We all love python for its simple code structure and readability. Moreover, Python is extensively used for Data Science, thanks to the immensely popular open source python libraries. Python provides cross-platform support and is compatible with almost all major systems. This makes it very easy to deploy and work with almost anywhere.
Yes, we all love python |
Although there are so many web frameworks available, python frameworks always stand out when the server-side calculations are to be done in python (ML, DL domains). This post is dedicated to such domains where a Data Science project is to be deployed over a web framework to access it via an API.
Why Flask?
It doesn't matter whether you are a Front-end developer looking to create a Backend service for your website or a Data Scientist looking to create an API for your Data Science project, python is a great choice to manage the Backend service of your website. There are two very popular Python-based Web frameworks - Django and Flask.
The main advantage of using Flask over Django (another python framework) is that Flask is very lightweight and comes with minimalistic features that are very easy to learn and implement. It gets things done pretty quickly so you can focus more on the domain rather than the backend service. It can turn out to be the best framework to make API calls to a server, and many programmers (including me) used it as their first proper web framework.
What is Flask?
Flask is a Micro Web-Framework that is used for developing Backend Interface for your Application. It is a lightweight framework that has a small footprint and can be used to set up things pretty quickly, with a simple yet extensible core. While we talk about Backend, we must understand that it is the service that sends data from the Server to a User, who is present at the Client-Side.
First things first - Understanding the web
The web works in a straightforward way - there is a Frontend which is displayed to the client on the browser, and there is a Backend which serves all the request made by the client. Let's understand this with an example. If you open the home page of Facebook, the web page that is visible on your browser is called the frontend of the application. It is responsible to communicate with the user and make calls to the backend to fulfill user requests. The backend part of Facebook can be the various features that run Facebook - login, signup, post, comment, etc. Now the main question is how do we connect the backend to the frontend?
REST API connects the front end to the backend
We make use of something called REST API. It stands for REpresentational State Transfer Application Programming Interface. It basically follows the HTTP protocol to send HTTP requests to the server (client to server) and receive HTTP responses from the server (server to client). Flask helps us create these REST APIs so that we can establish effective communication between our server and the client.
Every API consists of four parts - Endpoint, Method, Header, and Body. Each part is responsible for some work in the communication process. The Endpoint defines the URL where the server is to be contacted. The method defines the HTTP method used to send the request - GET, POST, DELETE, PUT. The header usually contains some authentication information of the client and other metadata. The body contains the actual data to be interpreted.
Now with the knowledge of REST APIs, we are ready to configure our system to work with Flask.
Configurations
At this point, python must be installed on your machine and it is advised to upgrade the python version to 3.X if you are not already using python3. The first thing which I would like you to do is create a virtual environment.
A virtual environment isolates all the libraries and packages that you need for an application from the global libraries so that you do not mess around with the global ones. It's very easy to mess up with libraries and packages in python because of its huge open-source library collection. Hence, it is advised to use a virtual environment for the application. You can create a virtual environment by following these steps:
1. $ pip install virtualenv : This will install the virtual environment
2. $ virtualenv env : This will create a new virtual environment named env in your current directory. Be sure to be in the right folder where you would like to make the entire application.
3. $ activate : This will activate the virtual environment so you can work in it. After working, you can similarly use $ deactivate to end the virtual env session.
After following these steps, you would be in your virtual environment. Now, we need to install Flask in the virtual environment. It is very easy to do so using pip.
$ pip install flask : This will install Flask for you(easy, right)
This ends the configuration part. Next, we move on to create a very basic Flask application to test our understanding of Flask.
Writing your first Flask application
We will keep the first application very simple. We will make a simple API gateway to two URLs - /home and /date using Flask. Open any text editor of your choice and create a file called app.py in the folder where the virtual environment is created. This file will contain the code to implement these APIs.
Lines 1 and 2 import the necessary classes from the flask package. Here, we import the Flask class to initialize our flask application and jsonify to convert python dictionaries as JSON data.
Line 3 creates an object of class Flask and passes the name of the function we are currently in (since we are at global level, __name__ contains "__main__". After the instantiation of our app object, we are ready to create our APIs.
API is sent to a route. That route is defined while calling the backend services. Each route has different functionalities. To create our API, we first associate it to a route and for that route, we define a function that handles the route.
The first API is /home which is routed to / (default home page). Line 5 describes that if we get any URL having an endpoint at "/" then it should be passed on to the function written below that router. Line 5 defines a router and Line 6 is a route handler, that is, how do we handle it once we reach the desired route. Inside the route handler function, we simply return a JSON object with a message that will be displayed on the client's browser.
The second API is the /date which is routed to /date. Line 8 traps the API call to "/date" and passes it to the route handler defined below it in Line 9. The route handler function makes use of python libraries to get the current date and wraps it in a JSON object.
Lines 13 and 14 are simple configuration which tells the application object to run if we are in the current function. app.run is used to actually make the server up and running. The IP address passed to it as an argument is where we want the server to be running. Since we are in our machines, we can give the localhost address.
Running the application
After writing the app.py, save it in the correct folder and make sure you have activated the virtual environment. Now to run the application, simply open your command line and type
$python app.py
This will run your flask server on port 5000 and take you to localhost:5000/ which is routed to our API handler and the Hello message will be displayed. You can navigate to localhost:5000/date to access the /date API and get the current date and time on your browser.
Pretty easy, isn't it? Voila! you successfully built a basic Flask server in under 15 lines.
In the coming posts, we will explore more about Flask with uses such as passing data to the backend and rendering dynamic content on the client-side. Stay tuned!
Feel free to ask doubts and/or appreciate the blogs in the Comment section. Thank You.
0 Comments