Before getting started, let find out some concepts:
What is Flask?
Flask is a “micro” Python framework for developing web services and REST APIs, which is lightweight, simple but extensible.
”Micro” means it does not includes any other tools or libraries, no database abstraction layer as other related frameworks like Django.
What is REST API?
REST (REpresentational State Transfer) as a set of conventions taking advantage of the HTTP protocol to provide CRUD (Create, Read, Update, and Delete) behaviour on things and collections of those things.
You can perform these actions on a thing or resource. A URL should identify a unique resource on the web, something that will work with the same thing over and over again for the same URL
Setting up Virtual Python Environment
To avoid any conflict with other existing Python installation, we should setup a virtual and “isolated” Python environment.
You can use Python venv to create a new virtual environment (env):
python3 -m venv <env_name>
Then activate that env by running the following command
My favourite VE is conda. The VE creation and activation is similar:
conda create -n <env_name> python=<version>
Activate and deactivate environment
# To activate this environment, use conda activate flask # To deactivate an active environment, use conda deactivate
pip to install Flask
pip install Flask
python-dotenv to embed Flask environment variables into
pip install python-dotenv
Freeze (embed) all installed pip packages to
pip freeze > requirements.txt
Write “Hello Flask” program
app.py and start writing the first Flask program
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello Flask!"
At the same folder of
app.py (the default Flask app name), run the following command to start the “Hello Flask” program locally
By default, our program will use port 5000. We can open the browser and access the URL
Turn on Development mode (auto reload if there is any changes in source code) and run the Flask program by the combined command as below
FLASK_ENV=development flask run
If the Flask python filename is not
app.py (for example
flask run will not work. So, we need to set another environment
We can also include all environment variables in
.flaskenvfile and put it in the same folder with
flask run to execute the Flask program.
If you can see “Hello Flask!”, then Congratulations, all done!