Install Flask and Create a Route
Install Flask and create a first route — Python web development. A short, practical lesson for step-by-step learners.
Focus: install flask and create a first route
You've written Python scripts that crunch numbers or process files, but when you try to turn that logic into something a user can actually click, type into, or see in a browser, the walls go up. Maybe you've copy-pasted a "Hello World" Flask snippet from a blog post, only to stare at an empty terminal or a ModuleNotFoundError. The pain is real: the gap between knowing Python and shipping a web app feels enormous — but it doesn't have to be. By the end of this lesson, you'll have Flask installed, a running dev server, and your very first route responding to HTTP requests — the foundation for every API and web app you'll build from here on out.
The problem this lesson solves
Every web framework — Django, FastAPI, Flask — starts with the same two questions: How do I install it? and How do I make it respond to a URL? Without a clear answer, you end up fighting your own environment instead of building features.
The core problem is that a Python script and a web application are fundamentally different animals. A script runs top-to-bottom and quits. A web app stays alive, listening for requests on a network port, and responds based on the URL path and method (GET, POST, etc.). If you've never set up a web server, the concept of "binding to localhost:5000" can feel like magic — and magic is where bugs hide.
This lesson removes that magic. You'll learn the precise, minimal steps to install Flask and create a first route, so you can move from "script thinking" to "web thinking." This is the same pattern you'll use for every route you add later in this track: a function in Python, decorated with a URL, returning a response.
Core concept / mental model
Think of Flask as a switchboard operator for your Python code. When a request comes in (a visitor types a URL in their browser), Flask looks at the URL and the HTTP method, then routes that request to the correct Python function — the one you've flagged with a @app.route() decorator.
In the diagram above, the browser sends GET / to Flask. Flask matches that route to the Python function index(), runs it, and sends back the returned string. The key idea: a route is a mapping between a URL pattern and a Python function.
Let's define the terms you'll see everywhere in Flask docs:
- Route — a URL pattern (e.g.,
/,/about) that the app listens for. - View function — the Python function that runs when a route is matched.
- Decorator —
@app.route("/")attaches URL information to the function below it. - Development server — Flask's built-in web server (
app.run()) for local testing. - Virtual environment — an isolated directory for your project's dependencies (we'll use one now, it saves you from dependency hell later).
The mental model to hold onto: Flask doesn't serve your whole Python script at once. It only runs the specific view function that matches the incoming request. That's how a single app can handle dozens of URLs without re-running the entire file.
How it works step by step
Now let's walk through the exact steps you'll take to install Flask and create a first route. This is the "cause → effect" sequence that gets a working web app.
- Set up a virtual environment — This isolates your project dependencies. Use
python -m venv venv(orpython3on Linux/macOS). - Activate the environment — On Windows:
venv\Scripts\activate; on macOS/Linux:source venv/bin/activate. Your terminal prompt shows(venv)when it's active. - Install Flask —
pip install flaskpulls in Flask and a few small dependencies (Werkzeug, Jinja2, etc.). - Create your app file — Typically
app.pyorhello.py. Import Flask, create an app instance, and define a route. - Run the development server —
python app.pyorflask run(we'll use the first). The server prints a URL likehttp://127.0.0.1:5000. - Visit the URL in your browser — You should see the text your view function returned.
Each step builds on the last; the cause of a successful "Hello, World!" is the effect of a properly activated virtual environment and a correct route setup. Miss step 1 or 2, and you'll likely get a ModuleNotFoundError: No module named 'flask'.
Step-by-step mechanics:
- When you call Flask(__name__), the __name__ argument helps Flask find resources like templates and static files relative to your app.
- The @app.route("/") decorator registers the function in Flask's internal URL map.
- When a request matches, Flask calls the function with the request context, and whatever the function returns becomes the HTTP response body.
Hands-on walkthrough
Time to get your hands dirty. We'll create a minimal application with one route, run it, and see the result.
Step 1: Set up your project directory and virtual environment
Open a terminal and run:
mkdir flask-hello
cd flask-hello
python -m venv venv
Step 2: Activate the virtual environment
On macOS/Linux:
source venv/bin/activate
On Windows (Command Prompt):
venv\Scripts\activate
Your terminal prompt should now show (venv) at the start. If it doesn't, you've skipped this step.
Step 3: Install Flask
With the environment active, run:
pip install flask
You'll see output showing the installed packages. To verify, you can check the version:
python -c "import flask; print(flask.__version__)"
Expected output (the exact version may vary):
2.3.3
Step 4: Create your first Flask app
Now create a file named app.py in the same directory. Copy this complete example:
from flask import Flask
# Create the Flask application instance
app = Flask(__name__)
# Define the first route: the root URL "/"
@app.route("/")
def index():
return "Hello, Flask!"
# Run the development server if this script is executed directly
if __name__ == "__main__":
app.run(debug=True)
Step 5: Run the app
In your terminal (with the virtual environment still active), run:
python app.py
Expected output:
* Serving Flask app 'app'
* Debug mode: on
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
Now open your browser and go to http://127.0.0.1:5000. You should see:
Hello, Flask!
Congratulations — you just installed Flask and created a first route! The server is listening for requests, and your index() function is being called every time someone visits the root URL.
Step 6: Add a second route (optional sneak preview)
To see how routes scale, add another route for /about:
@app.route("/about")
def about():
return "About this Flask app."
Restart the server (Ctrl+C, then python app.py again) and visit http://127.0.0.1:5000/about. You'll see the new message. The pattern is identical: a decorator, a function, a return value.
Compare options / when to choose what
You've installed Flask via pip, but there are a few decisions you'll face. Here's a comparison to help you choose wisely.
Virtual environment vs. global install
| Option | Pros | Cons | When to use |
|---|---|---|---|
| Virtual environment | Isolates dependencies, avoids version conflicts | Extra command to activate | Always for projects — this track's standard |
Global pip install flask |
Quick, no activation needed | Can conflict with other projects, may need sudo on Linux/Mac |
Only for experimenting on throwaway machines |
Recommendation: Use a virtual environment. It's the industry best practice and the first thing recruiters and senior devs look for.
flask run vs. python app.py
| Command | How it works | Best for |
|---|---|---|
python app.py |
Runs the script, which calls app.run() explicitly |
Simple scripts; you can pass debug programmatically |
flask run |
Uses Flask's CLI, looks for app.py by default, reads environment variables |
Cleaner separation of config; avoids hardcoding debug=True in production |
Both work for a beginner. In this lesson we used python app.py for clarity — but once you're comfortable, switch to flask run for real projects.
Alternative: FastAPI or Django
This track uses Flask, but it's worth noting the landscape:
- Flask — Microframework, minimal, great for learning routing and HTTP fundamentals.
- FastAPI — Modern async, automatic OpenAPI docs; excellent for building APIs, but requires learning type hints and async early.
- Django — "Batteries included": ORM, admin panel, auth; steep learning curve if you haven't mastered routing.
For this lesson, Flask is the right choice because it keeps routing visible and understandable. Later, you can transfer the same mental model to any framework.
Troubleshooting & edge cases
Even with clear instructions, things go wrong. Here are the most common issues you'll hit — and the fixes.
ModuleNotFoundError: No module named 'flask'
This almost always means the virtual environment isn't active. Check your terminal prompt for (venv). If it's missing, activate it again. If it's active but the error persists, you might have installed Flask in a different environment (e.g., a system Python). Run which pip on Linux/macOS or where pip on Windows to see which pip you're using.
Port already in use
If you see OSError: [Errno 98] Address already in use (Linux/macOS) or OSError: [WinError 10013] (Windows), another process is on port 5000. Two fixes:
- Find and kill the process (e.g., lsof -i :5000 on macOS/Linux).
- Change the port in app.run(port=5001) and visit http://127.0.0.1:5001.
Browser shows 404 Not Found
If you visit http://127.0.0.1:5000/nonexistent, Flask returns a 404 because there's no route for that path. That's expected. But if you typed the correct URL and still get 404, double-check that you saved your file and restarted the server after making changes.
Debugger off vs. on
If you set debug=True, you get auto-reload and a detailed error page — great for development. But in production, never run with debug=True; it exposes sensitive information. For now, keep it on for learning.
Using the wrong Python interpreter
If you're still inside the virtual environment but python --version shows an unexpected version, you may have a corrupted environment. Recreate it:
rm -rf venv
python -m venv venv
source venv/bin/activate # or Windows activation
pip install flask
Edge case: Silent server start but no response in browser
This can happen if your firewall blocks the port or if you're using a remote server. In that case, bind to 0.0.0.0 temporarily to test: app.run(host="0.0.0.0"). But never do that in production without a reverse proxy.
What you learned & what's next
Let's recap what you accomplished:
- You understood the core idea of Flask routing: how
@app.route()maps URLs to Python functions. - You installed Flask in a virtual environment, following industry best practices.
- You created a first route (
/) that returns a response, and you added a second route (/about). - You ran the development server and interacted with your app over HTTP.
- You can now troubleshoot common installation and routing errors.
This is the foundation everything else builds on. In the next lesson, you'll learn about routes with parameters — how to capture dynamic values from the URL (like /user/<username>) and use them in your view functions. That's the next step toward building real, data-driven web apps.
Keep your virtual environment active and your app.py ready — you'll extend it in the next lesson.
Pro tip: Always commit your
requirements.txt(generate it withpip freeze > requirements.txt) so your project is reproducible. You'll thank yourself when you work on a new machine or with a teammate.
Practice recap
Create a new Flask project in a fresh virtual environment. Add two routes: / returning "Home page" and /fav returning "Your favorite route". Run the app and verify both respond correctly. Then, try adding a third route with an uppercase path (e.g., /ABOUT) and observe that Flask is case-sensitive by default — it will return 404 for /about unless you also define that exact route. This reinforces that each route is a precise mapping you control.
Common mistakes
- Forgetting to activate the virtual environment before running
pip install flaskorpython app.py— you end up withModuleNotFoundErroror installing into the wrong Python. - Using
app.run()without theif __name__ == '__main__':guard — the app may run twice or behave oddly when you later import it as a module. - Editing
app.pywhile the server is running withoutdebug=True— the changes won't appear until you manually restart the server. - Running on a busy port (5000 is common) without knowing how to change it — you see
OSError: [Errno 98]orWinError 10013.
Variations
- Use
flask runinstead ofpython app.py— it avoids hardcodingapp.run()and reads config from environment variables. - Install Flask with a specific version (e.g.,
pip install flask==2.3.3) to lock dependencies for reproducibility. - Create a
requirements.txtfile early (pip freeze > requirements.txt) so your project setup is one command away on any new machine.
Real-world use cases
- A startup's backend team sets up Flask with a virtual environment to prototype a REST API for their mobile app — this exact install-and-route pattern is the first commit in their repo.
- A data science team wraps a machine learning model in a Flask route to serve predictions over HTTP, letting other services call it via a simple POST request.
- A solo developer builds a personal blog flashcard app locally with Flask, then deploys the same app to a cloud server using Gunicorn — starting from the same first route.
Key takeaways
- Flask maps URL paths (routes) to Python functions via the
@app.route()decorator. - Always use a virtual environment to isolate project dependencies;
python -m venv venvand activate it before installing packages. - The development server is for local testing only —
debug=Truegives you auto-reload and detailed errors, but never enable it in production. - To see a custom response, create a Python file that imports
Flask, instantiates the app, defines at least one route function returning a string, and then runsapp.run(). - Common errors like
ModuleNotFoundError: No module named 'flask'and port-in-use are quick to diagnose by checking your environment and theapp.run()arguments. - The next step after a simple route is adding dynamic URL parameters — the same pattern, but with
<variable>placeholders in the path.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.