CodingNic

Flask Fundamentals

Routing

Flask Fundamentals 12 min read

Routing

Routing

Routing is how Flask maps URLs to specific functions in your application.

It determines what happens when a user visits a particular path.

What is Routing?

A route connects a URL to a Python function.

When a request comes in, Flask looks at the URL and decides which function to execute.

Basic Route

A simple route looks like this:

id="basic-route"
@app.route("/") def home(): return "Home Page"

When a user visits /, this function runs.

Multiple Routes

You can define multiple routes:

id="multiple-routes"
@app.route("/") def home(): return "Home" @app.route("/about") def about(): return "About Page"

Each route handles a different URL.

Dynamic Routes

Routes can accept dynamic values:

id="dynamic-route"
@app.route("/user/<name>") def user(name): return f"Hello, {name}"

Example:

  • /user/John → Hello, John
  • /user/Alice → Hello, Alice

Route Methods

Routes can handle different HTTP methods:

id="route-methods"
@app.route("/submit", methods=["GET", "POST"]) def submit(): return "Form Submitted"

This allows your app to respond differently based on the request type.

How Routing Works

Flask processes routes in this flow:

  • Request comes in
  • Flask checks the URL
  • Matches it to a route
  • Executes the function
  • Returns the response

Flask Routing Diagram

Why Routing Matters

Routing is the backbone of your application.

  • It defines how users navigate your app
  • It connects URLs to logic
  • It enables dynamic behavior

Challenge

Create routes that accept values from the URL.

What to do

  1. Create a new route with a variable in the URL:

    /user/<name>

  2. In the function:

    • Accept name as a parameter
    • Return a message like: “Hello, John”
  3. Create another route:

    /post/<id>

  4. Return a message like: “Post ID: 5”

What you should test

  • /user/Alice → should display “Hello, Alice”
  • /post/10 → should display “Post ID: 10”

Summary

  • Routing maps URLs to functions
  • Each route handles a specific path
  • Routes can be static or dynamic
  • Routes can handle different HTTP methods

In the next lesson, you’ll learn how to render HTML using templates.