python-backend
/

Flask Routing – Mapping URLs to Functions

Last Sync: Today

On this page

6
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Flask Routing – Mapping URLs to Functions

What is Routing?

Routing is the process of binding a URL to a specific Python function. In Flask, this is handled primarily through the @app.route() decorator. When a user visits a specific path, Flask identifies the associated function (called a 'View Function') and executes it to return a response.

  1. Basic and Dynamic Routing

Static routes are simple, but dynamic routes allow you to capture values from the URL and pass them as arguments to your function. This is vital for resources like user profiles or blog posts.

PythonRead-only
1
@app.route('/welcome')
def welcome():
    return "Welcome to the Flask App!"

# Dynamic route capturing a string
@app.route('/user/<username>')
def show_user_profile(username):
    return f"User: {username}"

  1. Variable Converters

By default, dynamic segments are treated as strings. You can use converters to ensure the data is of a specific type (int, float, path, uuid) before the function is even called. If the type doesn't match, Flask returns a 404 error.

PythonRead-only
1
@app.route('/post/<int:post_id>')
def show_post(post_id):
    # post_id is guaranteed to be an integer
    return f"Post ID: {post_id}"

@app.route('/file/<path:subpath>')
def show_subpath(subpath):
    # Captures the rest of the URL including slashes
    return f"Subpath: {subpath}"

  1. HTTP Methods

By default, routes only respond to GET requests. To build a RESTful API, you must explicitly list the methods the route should handle.

PythonRead-only
1
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return "Processing Login..."
    else:
        return "Showing Login Form..."

  1. URL Building with url_for

Never hardcode URLs in your application. Use url_for() to generate URLs based on the function name. This ensures that if you change the URL path in the decorator, all your links automatically update.

PythonRead-only
1
from flask import url_for

# Generates '/user/Kishore'
url = url_for('show_user_profile', username='Kishore')

Routing Summary

ConverterDescriptionExample
stringDefault (accepts any text without slashes)/page/<name>
intAccepts positive integers/user/<int:id>
floatAccepts positive floating point values/price/<float:val>
pathLike string but accepts slashes/storage/<path:file>
uuidAccepts UUID strings/transaction/<uuid:id>

Test Your Knowledge

Q1
of 3

Which converter would you use to capture a URL that contains multiple slashes (e.g., /uploads/images/logo.png)?

A
string
B
url
C
path
D
file
Q2
of 3

What is the default HTTP method for a Flask route if 'methods' is not specified?

A
POST
B
GET
C
ALL
D
PUT
Q3
of 3

How do you generate a URL for a function named 'profile' that takes a 'username' argument?

A
url_for('profile', username='user1')
B
redirect('/profile/user1')
C
flask.get_url('profile', 'user1')
D
url_for('/profile/<username>')

Frequently Asked Questions

What is the difference between /path and /path/ (Trailing Slashes)?

If a route is defined as /path/, visiting /path will result in a 301 redirect to /path/. If defined as /path, visiting /path/ will result in a 404 error. It is best practice to include the trailing slash for 'folder-like' URLs.

Can one function have multiple routes?

Yes! You can stack decorators: @app.route('/') @app.route('/home') def index(): return 'Hello!'

What are Blueprints in Flask routing?

Blueprints are a way to organize your application into distinct components (e.g., auth, admin, api). They allow you to define routes in separate files and group them under a common URL prefix.

Previous

flask introduction

Next

flask templates

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.