Skip to content

Getting started with routes

Now that we have a basic understanding of how to set up a Flask application, let’s create a simple website with a few pages (routes).

Defining routes

In Flask, a route is a URL pattern that the application can respond to. When a user visits a URL, the application will execute the code associated with that URL. Routes are defined using the @app.route decorator.

Assuming we are building a simple website with the following pages on the example.com domain we can match up routes as follows:

Creating a simple website

Let’s create a simple website with the following routes:

  • Home page (/)
  • About page (/about)
  • Contact page (/contact)

To add a new route we need a decorator and a function that returns the content for that route. It is best practice to name the function the same as the route.

from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to the home page!"
@app.route("/about")
def about():
return "This is the about page."
@app.route("/contact")
def contact():
return "Contact us at: [email protected]"
if __name__ == "__main__":
app.run()

Returning HTML content

While we have just been returning simple strings in our routes, we can also return HTML content. This allows us to create more complex web pages with styling and formatting.

Let’s update our routes to return HTML content:

from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to the home page!"
return "<h1>Welcome to the home page!</h1>"
@app.route("/about")
def about():
return "This is the about page."
return "<h1>About us</h1><p>This is the about page.</p>"
@app.route("/contact")
def contact():
return "Contact us at:
return "<h1>Contact us</h1><p>Contact us at: <a href="mailto:contact@example.com">[email protected]</a></p>"
if __name__ == "__main__":
app.run()

Now when you visit the home page, about page, or contact page, you will see the HTML content returned by the routes.

Variable routes

In Flask, we can also define routes that accept variables. This allows us to create dynamic routes that can accept user input.

To define a variable route, we use <variable_name> in the route pattern. The variable name is passed as an argument to the route function.

String Routes

Let’s create a route that accepts a username and displays a personalized greeting:

@app.route("/user/<str:name>")
def user(name: str):
return f"Hello, {name}!"

Now when you visit /user/john, you will see the message Hello, john!.

Integer Routes

We can also accept integers as variables:

@app.route("/square/<int:num>")
def square(num: int):
return f"The square of {num} is {num*num}."

Now when you visit /square/5, you will see the message The square of 5 is 25..