Your First Flask App

Build your first Flask hello world app in this hands-on Python web development tutorial. Learn the core concept, step-by-step setup, troubleshooting, and what to study next.

Focus: build your first flask hello world app

Sponsored

Staring at a blank app.py file is the moment every web developer hits. You know the syntax, you can write functions, but where does a web app actually start? The pain is real: online tutorials show you a Flask snippet, but they miss the critical setup, the virtual environment, the directory structure, and the tiny mistakes that turn 'hello' into '404 Not Found'. This lesson ends that confusion by walking you through building your first Flask hello world app from scratch — so you can go from zero to a running web server in under ten minutes.

The problem this lesson solves

You have finished the basics of Python — variables, loops, functions — but now you want to show something to the world. Building your first Flask hello world app solves three problems at once:

  • You need a way to serve dynamic content, not just print to a terminal.
  • You need a minimal, understandable framework that doesn’t overwhelm you with configuration.
  • You need a mental model for how web frameworks work — routing, requests, and responses — before you move to more complex projects.

The alternative is writing raw socket servers or stitching together HTTP libraries — a painful and error-prone route that distracts from the actual goal of delivering value to users. Flask gives you a clean, beginner-friendly path that scales with you later.

Pro tip: You don’t need to master HTTP to build a hello world app. But understanding that every web request hits a function and gets a response will make every future Flask lesson easier.

Core concept / mental model

Think of Flask as a reception desk for your Python code. When a visitor (a browser, a curl command, a mobile app) arrives with a request — say, GET /hello — the reception desk checks its list of known routes and forwards the call to the right handler. That handler runs Python code, builds a response (usually HTML), and the desk sends it back.

  • Route: A URL like / or /hello that your app listens for.
  • View function: A Python function that returns what the browser should see.
  • App instance: The Flask object that coordinates everything.
  • Development server: A built-in server Flask provides for testing — not for production, but perfect for learning.

Here’s an ASCII mental model:

Browser/Git Bash → HTTP request → Flask (routing) → view function → HTTP response → browser

Flask is a micro-framework: it gives you core tools (routing, templates, request handling) but stays out of your way. Unlike Django, you’re not forced into a rigid project structure. That flexibility is perfect for a first app.

How it works step by step

Building your first Flask hello world app can be broken into five logical steps. Follow them in order, and you’ll have a working web server — even if you don’t fully understand every line yet.

  1. Install Python (if not already installed) — Flask requires Python 3.10 or newer.
  2. Create a project folder and set up a virtual environment — this isolates your project’s dependencies.
  3. Install Flask using pip inside that environment.
  4. Write the app.py file with the Flask app and a route.
  5. Run the development server and visit http://127.0.0.1:5000 in your browser.

Setting Up a Virtual Environment

A virtual environment is like a sandbox for your project. It prevents package conflicts and keeps your system Python clean. On macOS/Linux use python3 -m venv venv, on Windows use py -m venv venv. Activate it with source venv/bin/activate (macOS/Linux) or venv\Scripts\activate (Windows).

The Flask App Code

Open your editor, create a file named app.py, and write the classic piece of Flask:

# app.py
from flask import Flask

app = Flask(__name__)

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

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

Let’s dissect this:

  • from flask import Flask imports the core class.
  • app = Flask(__name__) creates the app instance — __name__ helps Flask locate resources.
  • @app.route('/') is a decorator that binds the URL / to the function below.
  • def hello_world(): returns a string, which Flask sends as the HTTP response.
  • if __name__ == '__main__': ensures the server only runs when you execute this file directly.

Running the Server

In your terminal, run:

python app.py

You should see output similar to:

 * Serving Flask app 'app' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
 * Debug mode: on
 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

Open that URL in your browser and you’ll see “Hello, World!” displayed in large heading text. Congratulations — you just built your first Flask hello world app!

Hands-on walkthrough

Now it’s your turn. This exercise will cement the concepts. We’ll extend the basic hello world with a dynamic route that uses the user’s name — a natural next step after the static version.

Exercise 1: A Personalized Greeting

Create app.py with the following code:

from flask import Flask

app = Flask(__name__)

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

@app.route('/hello/<name>')
def hello_name(name):
    return f'<h1>Hello, {name}!</h1>'

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

Run the app and visit http://127.0.0.1:5000/hello/Ada — you should see “Hello, Ada!”. The <name> part is a dynamic URL segment that Flask passes to your function as a string.

Expected output in browser:

Hello, Ada!

Exercise 2: Returning JSON (tiny step toward APIs)

Web apps often return structured data. Modify your route to return JSON:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def root():
    return jsonify({"message": "Hello, World!", "status": "success"})

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

Now if you use curl http://127.0.0.1:5000/ in your terminal, you’ll get:

{"message":"Hello, World!","status":"success"}

Pro tip: Use debug=True during development. It gives you detailed error pages and auto-reloads the server when you save your file. Turn it off in production — you’ll learn why in later lessons.

Compare options / when to choose what

Flask isn’t your only choice for a Python web framework. Here’s a quick comparison to help you understand why Flask is perfect for your first app:

Framework Pros Cons Best For
Flask Minimal, flexible, huge community, easy learning curve You decide the structure, no built-in ORM/admin Small to medium projects, microservices, learning
Django Batteries-included, admin panel, ORM, security features Opinionated, heavier learning curve, more code to set up Large applications, full-featured sites, deadlines
FastAPI Async support, automatic OpenAPI docs, type hints Newer, less mature ecosystem than Flask Modern APIs, high concurrency, async endpoints

For a beginner building your first Flask hello world app, Flask’s minimalism lets you focus on core web concepts without distractions. Later in your journey, you can switch or add other frameworks based on project needs.

Variation: Flask blueprints — start using them when your project grows beyond a few routes. Blueprints allow you to organize routes into modular components, a topic we’ll touch in a future lesson.

Troubleshooting & edge cases

When you start, small mistakes can turn into confusing errors. Here are the most common issues and how to fix them quickly.

Common Mistakes

  • Forgetting to activate your virtual environment — you install Flask globally but run from the venv, or vice versa. The symptom is a ModuleNotFoundError. Fix: activate the right environment (source venv/bin/activate).
  • Running flask run without setting the FLASK_APP environment variable — you’ll see “Error: Could not locate a Flask application.” Fix: either use python app.py or set export FLASK_APP=app.py (macOS/Linux) or set FLASK_APP=app.py (Windows).
  • Binding the server to 127.0.0.1 — this makes your app only accessible on your machine. If you want it visible on your LAN, change the run call to app.run(host='0.0.0.0') (not recommended for production).
  • Editing app.py but not saving — with debug=True the server auto-reloads, but only if the file is saved correctly; sometimes browsers cache old responses. Hard-refresh with Ctrl+Shift+R.
  • Port already in use — if port 5000 is taken, Flask will throw an OSError: [Errno 98] Address already in use. Fix: change the port with app.run(debug=True, port=5001) or kill the conflicting process.

Edge Case: Invalid Route

If you visit a URL that doesn’t match any route, Flask returns a 404 Not Found page. This is normal — you haven’t defined that route. For example, visiting http://127.0.0.1:5000/foo after following Exercise 2 will show a Flask 404 page.

What you learned & what's next

You’ve just built your first Flask hello world app and you now understand the core pieces: the Flask instance, routes, view functions, and how the development server works. You also practiced extending the app with dynamic URLs and JSON responses — small wins that will power your momentum.

  • You can explain how Flask routes an incoming request to a Python function.
  • You can complete a practical exercise that runs a live web server.
  • You know how to troubleshoot the most common beginner errors.

What’s next in the Python web development track? You’ll build on this foundation by learning about templating with Jinja2 — how to write HTML files with dynamic placeholders so you can render more complex pages cleanly, instead of hardcoding HTML in Python. That’s exactly where real web apps start.

Practice recap

Now, open your terminal and build your own hello world Flask app from scratch. Add a dynamic route like /hello/<name> and then try returning JSON with jsonify. Push yourself one step further: create a second route that returns the current time using Python’s datetime module — you’ll feel the power of dynamic responses.

Common mistakes

  • Forgetting to activate the virtual environment before installing Flask — you get ModuleNotFoundError even after pip install.
  • Running flask run without setting FLASK_APP — Flask can’t find your app and errors out.
  • Binding to 127.0.0.1 when you want others on your network to visit your app — use host='0.0.0.0' instead.
  • Using debug=True in production — leaks sensitive info and allows arbitrary code execution when exploited.

Variations

  1. Use flask run command instead of python app.py — requires setting FLASK_APP or creating a wsgi.py file.
  2. Structure your app inside a package folder (app/init.py) instead of a single app.py — useful as projects grow.
  3. Start with FastAPI if you mainly build APIs and want automatic OpenAPI docs — but Flask is better for general web apps.

Real-world use cases

  • A developer building a personal site uses Flask to serve a portfolio with dynamic routes per project.
  • A startup’s microservice exposes an internal health-check endpoint returning JSON via Flask.
  • A data science team wraps a machine-learning model in a Flask app, providing a simple REST API for predictions.

Key takeaways

  • Flask’s core job is routing: an incoming URL triggers a Python function that returns a response.
  • Use a virtual environment for every Flask project to keep dependencies isolated.
  • The @app.route decorator maps URLs to view functions — add as many as you need.
  • Run the development server with debug=True for better error messages and auto-reload.
  • Always end your app file with if __name__ == '__main__': app.run() so it only runs when executed directly.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.