Flask routes (URL paths)


Lesson 6 of 14 · Python for the web

In the previous lesson we made our first Flask web application.

Now we will learn how Flask decides which Python code should run when a user visits a certain URL address.

In Flask this is done with routes.

What is a route?

A route is a link between a URL address and a Python function.

When a user opens a certain address, Flask runs the function that is linked to that route.

  • URL → Python function
  • Python function → the server's response

An example of a simple route


from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Home page"

@app.route("/contact")
def contact():
    return "Contact page"

app.run()

This code defines two URL addresses.

  • / → the home page
  • /contact → the contact page
Example URL addresses
http://127.0.0.1:5000 http://127.0.0.1:5000/contact

How does Flask find the right function?

The decorator @app.route() tells Flask which function to run for a certain URL.


@app.route("/contact")
def contact():
    return "Contact page"

If the user opens the address /contact, Flask runs the function contact().

The function can have any name, but it is good practice for the name to describe the page.

Dynamic routes

Flask also lets you create dynamic URL addresses.

This means that part of the URL can change.


@app.route("/user/<name>")
def user(name):
    return "Hello " + name

If we open the address:


http://127.0.0.1:5000/user/Mark

the server will show:

Result
Hello Mark

Dynamic routes with numbers

Flask can limit the type of the variable.


@app.route("/number/<int:id>")
def number(id):
    return "The number is: " + str(id)

Here Flask expects that part of the URL is a number.


Mini project – A user profile

Let us make an application that shows a user's profile through the URL address.


from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Home page"

@app.route("/profile/<name>")
def profile(name):
    return "<h2>User profile: " + name + "</h2>"

app.run()

How does this project work?

  • the URL contains the user's name
  • Flask passes the name to the function
  • the function generates an HTML response

The most commonly used parameter types

  • <string:name> – text
  • <int:id> – a whole number
  • <float:price> – a decimal number
  • <path:path> – part of a URL path

Related lessons


Frequently asked questions

What is a Flask route?

A route links a URL address with a Python function.

Can one application have several routes?

Yes. A Flask application can have a large number of routes.

What are dynamic routes?

They are URL addresses that contain changing values.

Why are routes important?

Routes decide how users reach the pages of a web application.