Skip to main content

Flask Basic Routing

Introduction

Routing is one of the most fundamental concepts in web development, and Flask makes it incredibly intuitive to implement. In Flask, routing refers to the mechanism of mapping URL patterns to the functions that should handle them. When a user navigates to a specific URL in your web application, routing determines which function gets executed to generate the appropriate response.

In this tutorial, we'll explore the basics of Flask routing, which serves as the foundation for building dynamic web applications.

Understanding Flask Routing

What is Routing?

Routing is the process of determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.).

In simpler terms, routing decides which function should execute when a user visits a specific URL in your application.

Basic Route Definition

In Flask, you define routes using the @app.route() decorator. Let's start with the most basic example:

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return 'Welcome to the home page!'

if __name__ == '__main__':
app.run(debug=True)

In this example:

  • We import the Flask class from the flask module
  • We create an instance of Flask called app
  • We use the @app.route('/') decorator to tell Flask which URL should trigger our function
  • The function home() returns the content we want to display when users visit the root URL ('/')

When you run this application and navigate to http://127.0.0.1:5000/ in your browser, you'll see:

Welcome to the home page!

Creating Multiple Routes

A real web application typically has multiple pages. Let's add more routes to our application:

python
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(debug=True)

Now our application has three different routes:

  • / - The home page
  • /about - The about page
  • /contact - The contact page

Route Parameters

Often, you'll need to capture values from the URL. For example, you might want to display a user profile page where the username is part of the URL. Flask makes this easy with route parameters:

python
from flask import Flask

app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that username
return f'User: {username}'

if __name__ == '__main__':
app.run(debug=True)

When you visit http://127.0.0.1:5000/user/john, you'll see:

User: john

The <username> part in the route is a variable that gets passed to the show_user_profile() function. You can capture multiple parameters in a single route.

Type Conversion

By default, route parameters are strings. However, Flask can automatically convert parameters to other types:

python
from flask import Flask

app = Flask(__name__)

@app.route('/post/<int:post_id>')
def show_post(post_id):
# post_id is an integer
return f'Post ID: {post_id}, Type: {type(post_id).__name__}'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# subpath accepts slashes
return f'Subpath: {subpath}'

if __name__ == '__main__':
app.run(debug=True)

Visiting http://127.0.0.1:5000/post/42 shows:

Post ID: 42, Type: int

And visiting http://127.0.0.1:5000/path/some/nested/path shows:

Subpath: some/nested/path

Available converters include:

  • string: (default) accepts any text without a slash
  • int: accepts positive integers
  • float: accepts positive floating point values
  • path: like string but also accepts slashes
  • uuid: accepts UUID strings

HTTP Methods

By default, routes only respond to GET requests. To handle different HTTP methods (like POST, PUT, DELETE), use the methods parameter in the route decorator:

python
from flask import Flask, request

app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Process login form
return 'Processing login credentials...'
else:
# Show login form
return 'Please log in'

if __name__ == '__main__':
app.run(debug=True)

This route handles both GET requests (to display a form) and POST requests (to process the form data).

URL Building

Flask provides a function called url_for() to build URLs dynamically. This is preferred to hardcoding URLs, as it makes your application more maintainable:

python
from flask import Flask, url_for, redirect

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('/redirect-to-about')
def redirect_to_about():
# Dynamic URL building
about_url = url_for('about')
return redirect(about_url)

if __name__ == '__main__':
app.run(debug=True)

When visiting /redirect-to-about, the application will redirect you to the /about page.

Real-World Example: Blog Posts

Let's create a more practical example of a simple blog routing system:

python
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# Mock database of blog posts
blog_posts = {
1: {
'title': 'Getting Started with Flask',
'content': 'Flask is a micro web framework written in Python...',
'author': 'John Doe'
},
2: {
'title': 'Flask Routing Explained',
'content': 'Routing is the process of mapping URLs to functions...',
'author': 'Jane Smith'
}
}

@app.route('/')
def index():
# In a real app, we'd return an HTML template
return 'Blog Home Page - All Posts'

@app.route('/post/<int:post_id>')
def show_post(post_id):
post = blog_posts.get(post_id)

if post:
# Build HTML dynamically (in practice, use templates)
return f"""
<h1>{post['title']}</h1>
<p>By {post['author']}</p>
<p>{post['content']}</p>
<a href="{url_for('index')}">Back to Home</a>
"""
else:
return 'Post not found', 404

@app.route('/posts/category/<category>')
def posts_by_category(category):
return f'Showing all posts in category: {category}'

if __name__ == '__main__':
app.run(debug=True)

In this example:

  • The / route serves as the blog's homepage
  • The /post/<int:post_id> route displays individual blog posts
  • The /posts/category/<category> route shows posts filtered by category

Summary

Flask's routing system is both powerful and intuitive. We've learned how to:

  1. Create basic routes with the @app.route() decorator
  2. Define multiple routes for different pages
  3. Capture URL parameters and convert them to appropriate types
  4. Handle different HTTP methods like GET and POST
  5. Build URLs dynamically using url_for()
  6. Apply routing concepts in a practical blog example

Understanding routing is essential for Flask development as it forms the backbone of how users interact with your web application. With these fundamentals, you can start building more complex applications that respond intelligently to user requests.

Exercises

To reinforce your learning, try these exercises:

  1. Create a Flask application with routes for a home page, about page, and contact page.
  2. Build a simple portfolio site with routes for different projects (e.g., /project/1, /project/2).
  3. Create a route that accepts multiple parameters, such as /user/<username>/posts/<int:post_id>.
  4. Implement a route that handles both GET and POST requests, displaying form data when submitted.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)