Before getting started, let’s 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
Getting started!
Setting up Virtual Python Environment
To avoid any conflict with other existing Python installations, we should set up 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
. <env_name>/bin/activate
My favourite VE is conda. The VE creation and activation is similar:
Create conda
environment
conda create -n <env_name> python=<version>
Activate and deactivate the environment
# To activate this environment, use
conda activate flask
# To deactivate an active environment, use
conda deactivate
Install Flask
Using pip
to install Flask
pip install Flask
Tips:
Install python-dotenv
to embed Flask environment variables into .env
file
pip install python-dotenv
Freeze (embed) all installed pip packages to requirements.txt
file:
pip freeze > requirements.txt
Write “Hello Flask” program
Create a app.py
and start writing the first Flask program
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello Flask!"
Let’s run!
At the same folder of app.py
(the default Flask app name), run the following command to start the “Hello Flask” program locally
flask run
By default, our program will use port 5000. We can open the browser and access the URL http://localhost:5000/
or http://127.0.0.1:5000
Tips:
Turn on Development mode (auto-reload if there are 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 api.py
), the flask run
will not work. So, we need to set another environment FLASK_APP=api.py
We can also include all environment variables in .flaskenv
file and put it in the same folder with api.py
file.
FLASK_APP=api.py
FLASK_ENV=development
Then, just flask run
to execute the Flask program.
If you can see “Hello Flask!”, then Congratulations, all done!