<img alt="python flask" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/python-flask.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

Python Flask is a microframework for building web applications in Python.

It is a very flexible and customizable framework that makes learning easy. As a result, it is a popular choice when building web servers. This article introduces Python Flask: what it is, how it compares to other frameworks, and how to create a basic application in Python.

What is Flask?

<img alt="Python flask" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/image-25.png/w=400" data- decoding="async" height="299" src="data:image/svg xml,” width=”400″>

Flask is a framework for building web servers in Python. Unlike other frameworks, it does not force the developer to conform to a particular directory structure.

In addition, it is unopinionated, allowing you to use whichever tools you prefer to perform actions such as connecting to a database and validating form inputs.

As mentioned, Flask is used to build web servers. A web server is software that responds to HTTP requests with the appropriate data and files.

Flask vs. Other Frameworks

This section will briefly compare Flask to two other popular frameworks – Django and Fast API. We will cover the benefits and limitations of using Flask over the other frameworks.

Flask vs. Django

Flask is a lightweight micro-framework. It offers developers simplicity and flexibility, allowing you to build as you go. However, this means you must do a lot of work yourself.

On the other hand, Django is a “batteries-included” framework that comes with many preconfigured tools. This enables you to build and ship faster. However, Django is not very flexible and has a steeper learning curve.

As a result, Flask is used for small and medium-sized projects, while Django is used for larger and more complex projects.

Also read: Differences Between Flask and Django

Flask vs. FastAPI

FastAPI is a relatively new framework for building APIs in Python. It is fast and easy to use. It provides built-in monitoring as a feature. However, it is a new framework with a relatively small ecosystem and community. In addition, its use is limited to APIs.

In contrast, Flask is more versatile as it can be used for both APIs and rendering static files. It is lightweight and relatively easy. However, it is slower than FastAPI.

Flask is best suited for web applications where you must render HTML, while FastAPI should be used to build APIs.

Also read: FastAPI vs. Flask: Which of the Two is Right For You?

How to Create an Application in Flask

In this section, we will build a simple Flask app to display some HTML and provide data through an API. The point of this is not to provide a comprehensive tutorial to Flask. Rather, the aim is to show you briefly what building a Flask app would look like.

Prerequisites

To follow this tutorial, you have to understand Python 3. In addition, familiarity with HTTP would be useful, though not required.

To create an application in Flask, you need to install Python first. If you need a guide on how to do so, here’s a video to guide you:

<img alt="YouTube video" data-pin-nopin="true" data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/maxresdefault.jpg64fafcc39e5d4.jpg" height="720" nopin="nopin" src="data:image/svg xml,” width=”1280″>

Create a Virtual Environment

First, create a project folder for the application. I am running my commands in Bash Terminal; therefore, I create a folder using the following command:

mkdir flask-tut

Next, navigate inside the folder using the command:

cd flask-tut

After navigating into the folder, create a virtual environment using this command. This ensures that the dependencies we will install do not conflict with dependencies from other projects.

python3 -m venv venv

This should create a venv folder, which you can see with the command:

ls
<img alt="create a venv folder" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-07-03-37-11.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Activate Virtual Environment

Activating a virtual environment is easy. Using the Bash terminal, enter the command:

source venv/bin/activate

Your terminal prompt should change from this $ to this (venv) $.

<img alt="(venv) $. " data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-07-03-46-56.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

For more information, here’s an article on virtual environments in Python.

Install Flask

With a virtual environment, we can proceed to install Flask. For that, we will use pip:

pip install Flask

That should download some files and install dependencies.

<img alt="dependencies" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-07-03-55-42.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Serving Some HTML

Next, we can begin working on the main.py file. This file will be the application’s entry point.

touch main.py

After creating the main.py file, open it with your preferred editor and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return '

Hello from Flask!

'

In the above code snippet, we started by importing the Flask class. Next, we instantiated the Flask class, passing in the __name__ variable. This is a built-in variable storing the name of the current module. Flask needs this to know where to find files. We stored the instance of Flask in the app variable.

Next, we created a function called index. This function returns the HTML we want to display to the user. Before the function definition, we used the @app.route decorator. This decorator converts a regular function into a Flask view function. This means the function’s return value will be converted to an HTML response.

To run the application, we use the command:

flask --app main run

The –app flag specifies where the application is. In this case, in main.py. The server should start running.

<img alt="server running" data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-07-04-48-35-2.png/w=840" decoding="async" height="533" src="data:image/svg xml,” width=”840″>

And if you open the browser on http://localhost:5000 or http://127.0.0.1:5000, you should see an h1:

<img alt="local host output" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-07-04-52-23.png/w=953" data- decoding="async" height="657" src="data:image/svg xml,” width=”953″>

Writing all our HTML in our Python code would generally be bad. Ideally, we would want to separate the Python from the HTML. The next section will look at how to serve standalone HTML files.

Serving an HTML File

In this section, we will write the code to serve an index.html file for our website. First, let’s create the index.html file. We will create this file inside the templates folder because that is where Flask looks for our HTML template

touch template/index.html

Next, open the file using your preferred editor and add the following code:



  
    
    
    
    Flask Website
  
  
	

Hello from Flask!

Next, reopen the main.py file we created earlier. Then add the following import at the top, just after the Flask import:

from flask import render_template

The render_template function we just imported enables us to serve HTML templates. To render an HTML file, we modify the index function to look like this:

@app.route("/")
def index():
    return render_template('index.html')

Stop the server (Ctrl C) and restart it using the following command:

flask --app main run

Reload the browser window, and you should see the following.

<img alt="browser output" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-07-05-17-51.png/w=914,h=630" data- decoding="async" height="630" src="data:image/svg xml,” width=”914″>

In this example, we are displaying a static HTML page. With Flask, you can also display templates by creating HTML templates and providing data. These templates follow the Jinja syntax. We will not cover this here for brevity, but I will link some good resources to learn Flask later.

Creating an API Route

Displaying HTML content is one function of web applications. The other is to serve data through an API route. In Flask, it is also easy to set up API routes. Add this code to the main.py file to create an API route at ‘/data’.

@app.route('/data')
def data():
    return { "status": "OK", "msg": "Hello from Flask API" }

If a function returns a dict or list, the value is converted to JSON and sent as a response. If you restart the server and open http://localhost:5000/data, you should see the following:

<img alt="server" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-07-06-54-48.png/w=914,h=630" data- decoding="async" height="630" src="data:image/svg xml,” width=”914″>

Resources to Learn Flask

❇️ The Flask documentation is excellent for learning. It is well-structured, clear, and is probably the most reliable resource for learning Flask.

❇️ freeCodeCamp also has a great YouTube video on Flask. freeCodeCamp is a household name for free but great-quality learning resources.

❇️ This Udemy course is a good way to learn how to build enterprise-grade APIs in Flask. It covers tools such as Flask-SQLALchemy and Flask-Smorest.

Conclusion

This article was a brief introduction to Python Flask. We covered what it is, compared it to other web frameworks, and built a simple application. Lastly, I linked resources for further learning.

Next, check out how to secure a Flask REST API with a JSON web token.