Last modified: Nov 15, 2024 By Alexander Williams

Flask app.route() Guide: Define URL Routes Like a Pro

If you're building web applications with Flask (if you haven't installed Flask yet, check out our Flask Installation Guide), understanding app.route() is crucial for handling URL routing.

What is app.route()?

app.route() is a decorator in Flask that maps URL paths to view functions. It's how Flask knows which function to execute when a specific URL is requested.

Basic Route Definition


from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to Homepage'

@app.route('/about')
def about():
    return 'About Us Page'

Handling HTTP Methods

By default, routes only handle GET requests. Use the methods parameter to specify allowed HTTP methods.


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return 'Processing login...'
    return 'Please login'

Dynamic Routes with Variables

Flask allows you to create dynamic routes using variable rules. These variables are passed to your view function as arguments.


@app.route('/user/')
def show_user(username):
    return f'User Profile: {username}'

@app.route('/post/')
def show_post(post_id):
    return f'Post ID: {post_id}'

URL Building

Use url_for() to generate URLs for your routes dynamically. This is particularly useful when creating links in templates.


from flask import url_for

@app.route('/')
def index():
    user_url = url_for('show_user', username='john')
    return f'User URL: {user_url}'

Multiple URL Rules

You can map multiple URLs to the same function using multiple route decorators. This is useful for handling different URL patterns that should return the same content.


@app.route('/projects/')
@app.route('/our-work/')
def projects():
    return 'Our Projects'

Error Handling Routes

Define custom error handling routes using errorhandler decorator to provide better user experience when errors occur.


@app.errorhandler(404)
def page_not_found(error):
    return 'Page not found!', 404

Conclusion

Understanding app.route() is fundamental for Flask development. It provides flexible URL routing capabilities for building robust web applications. Ready to see it in action? Check out our render_template guide for the next step.