Flask Tutorial: Understanding Routes with Examples

Flask is a lightweight and flexible Python web framework that is perfect for building web applications quickly and efficiently. One of the core concepts in Flask is routing. Routing is the mechanism by which Flask maps URLs to functions, allowing you to create dynamic web applications. In this tutorial, we'll dive deep into Flask routes with examples to help you understand how to create and manage routes effectively.



flask tutorial routes with examples


What is a Route in Flask?

A route in Flask is a URL pattern that is associated with a specific function in your application. When a user visits a URL, Flask matches the URL pattern to the corresponding function and executes it. The function then generates the response that is sent back to the user's browser.


Read also:

Setting Up Flask

Before we begin, let's ensure you have Flask installed.

pip install Flask

Next, let's create a simple Flask application. Create a file named `app.py` and add the following code:

from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':

This code sets up a basic Flask application. The `if __name__ == '__main__':` block ensures that the Flask development server runs only when the script is executed directly, not when it is imported as a module.
Read also: Flask Tutorial: Templates

Creating Your First Route

Let's create a simple route that responds with "Hello, World!" when accessed. Add the following code to `app.py`:

def hello_world():
    return 'Hello, World!'

In this example, the `@app.route('/')` decorator maps the root URL (`/`) to the `hello_world` function. When you visit `` in your browser, you should see "Hello, World!".

Dynamic Routes

Flask allows you to create dynamic routes by using variable rules. Variable rules are specified within angle brackets (`<>`). Here’s an example:

def show_user_profile(username):
    return f'User: {username}'

In this route, `<username>` is a variable part of the URL. When you visit ``, Flask will pass `dailyaspirants` as the `username` argument to the `show_user_profile` function, and you will see "User: dailyaspirants" displayed.

Type Converters

Flask also supports type converters to specify the type of the variable. The default type is `string`, but you can specify other types such as `int`, `float`, and `path`. Here’s how you can use type converters:

def show_post(post_id):
    return f'Post {post_id}'

In this example, `<int:post_id>` ensures that the `post_id` variable is an integer. If you try to access a URL like ``, Flask will return a 404 error because `abc` is not an integer.

Handling Multiple Routes

You can use the same function to handle multiple routes by passing a list of URL rules to the `@app.route` decorator:

def greet():
    return 'Hello or Hi!'

With this setup, both `` and `` will trigger the `greet` function and return "Hello or Hi!".
Read also: Implementing Basic Add to cart functionality in python using Flask

Using URL Parameters

Sometimes, you might want to add query parameters to your URLs. Flask makes it easy to access these parameters using the `request` object. First, import the `request` object:

from flask import request

Next, create a route that handles URL parameters:

def search():
    query = request.args.get('q')
    return f'Searching for: {query}'

When you visit ``, Flask will extract the query parameter `q` and pass it to the `search` function, resulting in "Searching for: flask".

Returning JSON Responses

Flask makes it easy to return JSON responses using the `jsonify` function. First, import `jsonify`:

from flask import jsonify

Then, create a route that returns a JSON response:

def get_data():
    data = {'name': 'John', 'age': 30}
    return jsonify(data)

When you visit ``, Flask will return a JSON response containing the data dictionary.

Creating an HTML Form

Let's create an HTML form that sends data via a POST request. Create a folder named `templates` in the same directory as `app.py`, and inside this folder, create a file named `form.html` with the following content:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Form</title>
    <h1>Submit Your Name</h1>
    <form action="/submit" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <button type="submit">Submit</button>

Handling the POST Request in Flask

Now, let's update `app.py` to render the form and handle the form submission. Add the following code:

from flask import Flask, request, render_template

app = Flask(__name__)

def index():
    return render_template('form.html')

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f'Hello, {name}!'

if __name__ == '__main__':


1. Rendering the Form: The `index` route renders the `form.html` template, displaying the HTML form when the user visits the root URL (`/`).

2. Handling Form Submission: The `/submit` route is configured to handle POST requests (`methods=['POST']`). When the form is submitted, the data is sent to this route. The `request.form` dictionary is used to access the form data. In this case, `request.form['name']` retrieves the value of the input field with the name attribute `name`.

3. Response: After retrieving the name from the form, the function returns a response that includes the submitted name.


Routing is a fundamental concept in Flask that allows you to map URLs to functions and create dynamic web applications. In this tutorial, we covered the basics of creating routes, dynamic routes, type converters, handling multiple routes, using URL parameters, and returning JSON responses.

With these examples, you should have a solid understanding of how to work with routes in Flask.

Previous Post Next Post