JustPaste.it

Using Flask to Build RESTful APIs with Python

Introduction to Flask:

 

Flask is one of the most popular frameworks in Python. It is mainly used to build small size to medium size applications. One of the best aspects of Flask is that it is a bare minimum framework that one can customize as per their need.

using_flask_to_build_restful_apis_with_python_meta_21.jpg

Flask has also gained much popularity in the Data Science community. Data Scientists can quickly create and deploy APIs for the models in production. Along with backend API, we can render frontend, as Flask leverages Jinja2 to render HTML templates.

 

Flask is a good option if one has to build a microservice-based architecture. This means we can build small self-contained services which can later be easily integrated into another extensive application. For example, an application is built in NodeJS and serves the need quite nicely. Still, a few machine learning-based features are to be added to the application, for which we can create separate services for each ML model and integrate the API in the NodeJ application. 

Many popular applications are built using Flask. Netflix and Uber are some popular applications that use Flask as the backend.

 

Bootstrapping a Flask Application

1. Check the python version: The first step is to check if you have python installed on your system. You can do this using the below command and get the output in the following line.

If you don't get this output, python is missing from your system. You can refer to the links to install python for windows. Mac and Linux-based systems usually come with pre-installed python

9fbfb7ac6c2b3fd83c0d8e807f4dee1a.png

2. Check pip: Next, we check if pip is installed with the below command. 

If pip is not present, you can install it using the below commands:

1c2ce6c5fa2a2dbc5897200915b88097.png

 

  • Windows: py -m ensurepip --upgrade
  • Linux: python -m ensurepip --upgrade
  • MacOS: python -m ensurepip --upgrade

 

3. Flask Installation: Now that we have python and pip ready, we can proceed to install Flask using the command 

  •  pip install flask

f888fb182b46fb0932377fbc8dd98d2e.png

 

 

To confirm if the installation was successful, use the following steps. 

 

4. First Flask program: Let's build our first Hello World Program using Flask. To do this, create a new file and name it hello.py. You can use the editor of your choice to write the below code.

Save the file, and in the same directory run 

 

  •  flask --app hello run

 

The output would look like this.

On the browser of your choice, enter: Http://127.0.0.1:5000.

If you can see the above screen, congrats on your very first flask program.

Click to know more