Skip to main content

Your First Flask App: 'Hello, Web!' (Part 1)

With our environment set up, it's time to write our very first web application with Flask. The traditional starting point for any new programming endeavor is the "Hello, World!" application. We'll create a simple web server that, when accessed, returns that classic phrase to the user's browser.

This article covers the absolute minimum code required to get a Flask application up and running, focusing on the basic structure and the concept of routing.


📚 Prerequisites

You should have a project folder with an active virtual environment and Flask installed, as described in the previous article. You should have a file named app.py inside this folder.


🎯 Article Outline: What You'll Master

In this article, you will learn:

  • The Minimal Flask App: The essential lines of code needed to create a Flask application.
  • The Application Instance: What app = Flask(__name__) means.
  • Routing with Decorators: How to use the @app.route() decorator to connect a URL path to a Python function.
  • View Functions: Understand the role of the function that handles a request and returns a response.
  • Running the Development Server: How to start your app and see it in your browser.

💻 Section 1: The Code for "Hello, Web!"

Open your app.py file and enter the following code. This is a complete, working Flask application.

# app.py

# 1. Import the Flask class
from flask import Flask

# 2. Create an instance of the Flask class
# __name__ is a special Python variable that gives each file a unique name.
# Flask uses this to know where to look for resources like templates and static files.
app = Flask(__name__)

# 3. Define a route and the view function that will handle it
@app.route("/")
def hello_world():
"""This is a view function that returns a response."""
return "<h1>Hello, World!</h1>"

# 4. (Optional but recommended) A block to run the app with the dev server
if __name__ == "__main__":
# The 'debug=True' part will automatically reload the server when you make changes
app.run(debug=True)

🧠 Section 2: Breaking Down the Code

Let's go through each part of the script.

Part 1: from flask import Flask

This line imports the main Flask class from the flask library that we installed with pip. All our application's functionality will stem from an object of this class.

Part 2: app = Flask(__name__)

Here, we create an instance of the Flask class. This app object is the heart of our web application. We pass it the special variable __name__, which Python sets to the name of the current module. Flask uses the location of this module as a starting point to find other files like HTML templates, which we'll see in later articles.

Part 3: @app.route("/") and the View Function

This is the core of Flask's routing mechanism.

  • @app.route("/"): This is a Python decorator. It modifies the function that comes immediately after it. In this case, it registers our hello_world() function as the handler for the root URL of our website (/).
  • def hello_world():: This is our view function. It's just a regular Python function. Its job is to handle an incoming request for its associated route and return the response that should be sent back to the browser.
  • return "<h1>Hello, World!</h1>": The value returned by a view function is the body of the HTTP response. Here, we are returning a simple HTML string. The browser will receive this string and render it as a large heading.

Part 4: if __name__ == "__main__":

This is a standard Python construct. It ensures that the code inside it only runs when you execute the script directly (python app.py). If you were to import this file into another script, the app.run() line would not execute, which is the correct behavior.

  • app.run(debug=True): This method starts Flask's built-in development web server. It's a simple server that's great for testing and development, but it is not suitable for production use. Setting debug=True is highly recommended during development, as it will automatically restart the server every time you save a change to your file, and it will provide helpful debugging information in the browser if an error occurs.

🚀 Section 3: Running Your Application

  1. Make sure your virtual environment is active.

  2. Navigate to your project directory in your terminal.

  3. Run the application with the following command:

    python app.py

You should see output in your terminal that looks something like this:

 * Serving Flask app 'app'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: ...

This tells you that your development server is running and listening for requests at the address http://127.0.0.1:5000.

Now, open your web browser and navigate to that address. You should see a webpage with the text "Hello, World!" in a large heading.

Congratulations, you've just built and run your first web application!


✨ Conclusion & Key Takeaways

You've seen how just a few lines of Python code, thanks to the power of the Flask framework, can create a functioning web server.

Let's summarize the key takeaways:

  • A Flask app is an instance of the Flask class: app = Flask(__name__).
  • The @app.route() decorator is used to map a URL path to a view function.
  • A view function is the Python function that handles the request and returns the response.
  • app.run(debug=True) starts the built-in development server, which is perfect for testing your code locally.

➡️ Next Steps

Our first app is simple, but it only returns a basic string. Real web pages are built with HTML. In the next article, "Your First Flask App: 'Hello, Web!' (Part 2): Templates and Jinja2," we'll learn how to use HTML templates to build more complex pages.

Happy coding!