Hello World Flask: Create your first web app with Python

Video thumbnail

If you are taking your first steps in web development with Python, you now have your environment ready to develop in Flask,  you have surely heard of Flask, one of the lightest and most flexible frameworks for creating server-side applications.

In my case, when I started with Python frameworks, I discovered that Flask is the perfect candidate to start with: its minimalist structure lets you focus on understanding the server logic without getting distracted by unnecessary layers or modules.

Flask is a great web framework for creating server-side web applications with Python; if you don't have knowledge in using Python server web frameworks, Flask is a good candidate to start with; as a microframework, which means it initially brings the minimum necessary to function, you can gradually see how the framework works without leaving room for confusion with files, directory structure, or modules you haven't placed, as happens with other more robust frameworks like Django, which has many files and folders when creating a Django project.

What is Flask and why is it ideal for starting with Python

Flask is a web **microframework** for Python.

The term “micro” doesn't mean it's limited, but rather that it includes only the essentials to get an app running: an internal web server and a routing system.

What it means that Flask is a "microframework"

Being a microframework implies that Flask doesn't impose a rigid structure. You decide how to organize your code, which libraries to use, and how to scale your project.
That freedom is what makes it so attractive to beginners: you truly learn how each piece connects.

Differences between Flask and Django

When I tried Django, I was impressed by its robustness, but also by the number of folders and files it generates when creating a project.

With Flask, on the other hand, you can have a functional application in just a few lines of code, which makes it ideal for learning how a web application works from the inside.

Installing Flask and preparing the development environment

First of all, we are going to prepare the environment to create our app and our Hello World; first create a folder on the Desktop or where you want to have your project and give it a name, like first_app; then open your terminal on Linux or Mac or CMD on Window and navigate to that directory with the cd command.

The next step, which would be optional, is that you use an editor, such as Visual Studio Code VSC, but if you prefer you can even use blog notes; Now, we are going to create our first file, for that we enter the folder that you created in the first step (tasks) and create a file called app.py:

app.py app in Flask

Before writing code, we will configure the environment to avoid conflicts.

Create a virtual environment in Python for Flask

In your terminal or console:

$ python -m venv venv
$ source venv/bin/activate  # On Linux/Mac
$ venv\Scripts\activate     # On Windows

This isolates the project dependencies and prevents future errors.

Installing Flask with pip

With the environment active:

$ pip install Flask

That's it! You can now use Flask in your project. 

Creating your first “Hello World” with Flask

Finally, it's time to create the "Hello World" with Flask; that is, implement the minimum necessary to be able to see something on the screen.

Minimal structure of a Flask project

/tasks
└── main.py

So, we create a file inside the project (the tasks folder):

main.py

With the following code:

main.py

from flask import Flask 
app = Flask(__name__) 
 
@app.route('/') 
def hello_world() -> str: 
    return 'Hello Flask!' 
if __name__ == '__main__': 
    app.run() 

The previous code is a complete web application based on Flask; from this, we can understand the term microframework used to describe Flask, since it has the minimum necessary to function, therefore, a minimal implementation in Flask can be written in a few lines of code; the previous application will simply display "Hello Flask!" in the browser.

Line-by-line explanation of the code

  • from flask import Flask: we import the base class of the framework.
  • app = Flask(__name__): we create an instance of the application.
  • @app.route('/'): this decorator associates the hello_world() function with the root route ('/').
  • return 'Hello Flask!': what you will see in the browser.
  • app.run(): launches the internal development web server (Werkzeug).

Running the Flask application and seeing the result

We start the application with:

$ python main.py
Run app flask in terminal

And in the terminal you will see something like:

 * Serving Flask app 'main'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000

Now, if we navigate to the previous route:

http://127.0.0.1:5000. 

We will see a message of 

Hello Flask!

on the screen.

Let's analyze the previous code a bit more in detail; through:

from flask import Flask 
app = Flask(__name__) 

We import the Flask class, which is used to create an instance, called app, and from it, multiple configurations can be made at the project level, such as the database, sending emails, routing, among others, but, for now, it is only used to create a route:

@app.route('/') 

This decorator is used so that the function it decorates can be consumed by an HTTP request through the associated route; that is, in this example, the route '/' is assigned to the view function hello_world()

When a user accesses the route '/', Flask will execute the hello_world() function and return the text string "Hello Flask!".

Finally, the application is run with:

if __name__ == '__main__': 
    app.run() 

The previous conditional verifies if the current module is the main program being executed. If so, the code inside the if block is executed; which allows starting the web server that Flask uses internally: Werkzeug.

The if __name__ == '__main__': conditional ensures that the server only runs if the script is executed directly from the Python interpreter and **not from an imported module** (importado).

You can try returning HTML content instead of text like:

main.py

@app.route('/') 
def hello_world(): 
    return '<h1>Hello World!</h1>'

Enabling debug mode in Flask

The debugging mode or debug is an essential tool in the development of web applications since with it we can effectively develop the application, in addition to identifying and solving errors in the code quickly and efficiently. When the debugging mode is activated, errors with exact details will start to appear by the browser and Flask console and with this, understand exactly what is happening and correct the problem; In this post we will see how to activate the debug mode in Flask.

With our application created in Flask, the next thing that will interest you is to enable its debugging; and this is useful because without it, every time you make changes to the source code, you'll have to bring down the server and bring it up beforehand; which is a great hassle; so, to avoid this, we have the debug option, with True:

if __name__ =='__main__':  
    app.run(debug = True

With this, the server will reload automatically.

You can also do this from the configuration file that you have, which is recommended, to have your application well organized.

This was established in the previous Hello World, but it's important to mention it so you can keep it in mind when extending the application.

Common errors when starting with Flask and how to solve them

“Port 5000 already in use”

Port 5000 is occupied. Quick fix:

$ python main.py -p 5001

Flask doesn't show the page in the browser

Verify that you are in the correct folder and that the virtual environment is active before running python main.py.

Attempt to access a socket not allowed by your access permissions

This is a common security error, sometimes the OS won't allow the app to start; you can change the IP or port:

app.run(debug=True, host="0.0.0.0", port=5050)

Recommendations for beginners

  • Always use virtual environments.
  • Avoid using the development server in production.
  • Read the terminal messages: Flask gives very useful hints.

Conclusion and next steps

In this tutorial, we saw how to create, run, and understand a minimal application with Flask.
Personally, I liked that it allows you to learn from the base, without excessive configurations.
The next step is to explore:

Flask is the ideal starting point for growing into real projects. 

Frequently asked questions about Flask

What is Flask and what is it for?
It is a microframework for creating web applications in Python simply and flexibly.

How to create a “Hello World” with Flask step by step?
Install Flask, create main.py, define the '/' route, and run python main.py.

Why is it called a microframework?
Because it offers the minimum necessary to function, without imposing unnecessary structure or dependencies.

How to return HTML instead of text?
Change the function's return to an HTML string ('<h1>Hello World!</h1>').

What is the difference between Flask and Django?
Flask lets you build from scratch; Django already comes with a complete structure for large projects.

I agree to receive announcements of interest about this Blog.

We'll get started with Flask, the Python web microframework. We'll cover how to create a controller, set up its routes, and set up the development server, run it locally, and learn tips for beginners.

| 👤 Andrés Cruz

🇪🇸 En español