Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 72 ยท Getting Started

Setup and Your First App

Install Flask in a virtual environment, create your first Flask app with routes, and send requests to it with the test client. Includes live, runnable examples.

Getting started with Flask takes about five minutes. You create a virtual environment, install the package, write a file with a few lines of Python and run it. In this lesson you do each step, and you also get a version of the same app that runs right here in your browser.

The most important thing to take away is the shape of a Flask program: one Flask object, one function per page, and a decorator that connects the two. Everything else in the course grows from that.

Installing Flask on your machine

These commands are read-only here, because they belong in your own terminal. Always give each project its own virtual environment so its packages do not mix with other projects (see Virtual Environments for the full story).

Terminal
# macOS and Linux
mkdir hello-flask && cd hello-flask
python3 -m venv .venv
source .venv/bin/activate
pip install flask
Terminal
# Windows (PowerShell)
mkdir hello-flask; cd hello-flask
py -m venv .venv
.venv\Scripts\Activate.ps1
pip install flask

pip install flask also installs Flask's dependencies: Werkzeug, Jinja2, MarkupSafe, ItsDangerous, Click and Blinker. You can check the result with pip list. A good habit is to record exact versions in a requirements.txt file with pip freeze > requirements.txt, so teammates and servers install the same packages (see Packages and pip).

Installing Flask in the browser

The examples in this course run in your browser, where there is no terminal. Instead of pip, they call micropip, the installer that ships with the in-browser Python:

Python Install and import Flask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The await works at the top level because the runner supports it. The second line prints True because a Flask application is a callable object, the WSGI interface from the previous lesson. In every later lesson the two micropip lines at the top play the same role as pip install flask on your machine.

Your first application

On your own machine, a complete Flask app fits in one file. Save this as app.py:

Python
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<h1>Hello, Flask!</h1>"

@app.route("/about")
def about():
    return "This site is built with Flask."

Then, with your virtual environment active, start the development server from the same folder:

Terminal
flask --app app run --debug

The terminal prints a local address, usually http://127.0.0.1:5000. Open it in a browser to see your heading, and add /about to see the second page. The --debug flag turns on the reloader (the server restarts when you save a file) and the interactive debugger. Never use debug mode on a public server. The next lessons cover the flask command in detail.

Look at the code piece by piece:

  • Flask(__name__) creates the application. __name__ tells Flask where your code lives, so it can find templates and static files next to it.
  • @app.route("/") is a decorator that registers the function below it as the handler for the path /. Such a function is called a view function, or just a view.
  • The view returns a string. Flask wraps it into a response with status 200 OK and the content type text/html.
flowchart LR
    A["Flask(__name__)<br/>creates the app"] --> B["@app.route('/about')<br/>adds a rule to the URL map"]
    B --> C["def about():<br/>the view function"]
    C --> D["return value<br/>becomes a response"]

Registering a route stores a rule that points at your function; the function's return value is what the visitor receives.

Choosing the host and the port

The development server listens on 127.0.0.1:5000 by default. 127.0.0.1 ("localhost") is reachable only from your own computer, which is what you want most of the time. Change the address or port with options of the flask run command:

Terminal
flask --app app run --port 8000                    # http://127.0.0.1:8000
flask --app app run --host 0.0.0.0 --port 8000     # reachable from other devices on your network
flask --app app run --debug --port 5050            # a free port if 5000 is taken

You can also set them with environment variables (FLASK_RUN_HOST, FLASK_RUN_PORT), put them in a .flaskenv file (project layout) or pass them in code with app.run(host="127.0.0.1", port=8000, debug=True) at the bottom of app.py when you start it with python app.py.

A few notes. 0.0.0.0 means "every network interface": handy for testing from a phone, but anybody on the same network can then reach your app (and, with debug on, run code through the debugger). On macOS, port 5000 is often taken by the AirPlay receiver, so use another port if you see "Address already in use". The built-in server is for development only; production uses a WSGI server (Deployment).

Each project should have its own virtual environment (.venv). Activate it each time you open a terminal, run deactivate when you finish, never commit the folder to Git (add .venv/ to .gitignore) and share requirements.txt instead, so anyone can rebuild it with pip install -r requirements.txt.

The same app, tested in the browser

Here is that app as a runnable example. Instead of opening a browser tab, we use the test client: it builds a request, hands it to the app and gives you back the response object.

Python First app and first requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two lines show two ways to read a body: get_data(as_text=True) gives a str, while .data gives raw bytes. The request to /missing returns 404 NOT FOUND automatically, because no rule matches that path.

More than one URL per view, and one view per URL

A view can have several @app.route decorators, and every route needs a unique function name, since Flask uses the name as the route's endpoint (you will use endpoints with url_for in a later lesson).

Python Several routes, endpoints and a typo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All three paths lead to the same view, and <name> captures part of the URL and passes it to the function as an argument (the next chapter covers this in depth). The last block shows a classic beginner mistake: defining a second function with the same name. Flask refuses it, because two different functions cannot share the endpoint index.

Tip: Flask looks for app.py or wsgi.py automatically, but naming the app explicitly with --app avoids guessing: flask --app app run. If your variable is not called app, write --app app:my_app.

What the view may return

So far the views returned strings. Flask is flexible about return values: a string becomes an HTML response, a dictionary becomes JSON, and a tuple can add a status code and headers. The Responses lesson covers all the forms. For now, remember the rule: a view must return something. Forgetting the return gives a TypeError, because Flask cannot turn None into a response.

Python A view that forgets to return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first request ends in 500 INTERNAL SERVER ERROR, the standard answer when your code raises an exception; the second shows a dictionary turned into a JSON response automatically. Error handling gets its own lesson later.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why create a virtual environment before running pip install flask?

    A virtual environment gives every project its own set of installed packages, so versions never clash between projects.
  2. 2. What does @app.route("/about") do?

    The decorator adds a rule to the app's URL map that points the path at the decorated view function.
  3. 3. What status does the test client report for client.get("/missing") when no route matches?

    Flask answers requests that match no rule with the standard 404 Not Found response.
  4. 4. Two views in one app are both named index. What happens?

    The function name becomes the endpoint, and endpoints must be unique, so Flask refuses to register a different function under the same name.
  5. 5. What does the micropip line do in the examples of this course?

    There is no terminal in the browser, so micropip installs packages for the in-browser Python runtime.

Summary

  • Create a virtual environment, then pip install flask; in the browser examples await micropip.install("flask") does the same job.
  • A Flask app is app = Flask(__name__) plus view functions registered with @app.route(...).
  • Run it locally with flask --app app run --debug; use debug mode only on your own machine.
  • The test client (app.test_client()) sends a request into the app and returns a response with status, status_code, data, get_data() and get_json().
  • Unknown paths return 404, errors in views return 500, and each view needs a unique endpoint name.

Next: How a Request Flows Through Flask, a closer look at what happens between the request arriving and the response leaving.