0
0
Flaskframework~5 mins

Trailing slash behavior in Flask

Choose your learning style9 modes available
Introduction

Trailing slash behavior helps Flask decide if a URL should end with a slash or not. It makes your web app handle URLs more flexibly and avoid errors.

When you want to create a route that works with or without a slash at the end.
When you want to redirect users to a consistent URL format.
When you want to avoid 404 errors caused by missing or extra slashes in URLs.
When designing RESTful APIs where URL structure matters.
When you want to improve user experience by handling URL variations smoothly.
Syntax
Flask
@app.route('/path/')  # redirects /path to /path/

@app.route('/path')  # 404 on /path/

Adding a trailing slash in the route means Flask will redirect URLs without the slash to the one with it.

Not adding a trailing slash means Flask will return 404 if the slash is added in the URL.

Examples
This route has a trailing slash. Flask will redirect '/hello' to '/hello/' automatically.
Flask
@app.route('/hello/')
def hello():
    return 'Hello with slash!'

# Accessing '/hello' redirects to '/hello/'
This route has no trailing slash. Flask expects exactly '/world' and will not accept '/world/'.
Flask
@app.route('/world')
def world():
    return 'Hello without slash!'

# Accessing '/world/' returns 404 error
Sample Program

This Flask app has two routes: one with a trailing slash and one without. Visiting '/greet' will redirect to '/greet/'. Visiting '/bye/' will cause a 404 error because the route does not have a trailing slash.

Flask
from flask import Flask

app = Flask(__name__)

@app.route('/greet/')
def greet_slash():
    return 'Greet with slash!'

@app.route('/bye')
def bye_no_slash():
    return 'Bye without slash!'

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

Flask's trailing slash behavior helps keep URLs consistent and user-friendly.

Use trailing slashes for routes that represent folders or collections.

Use no trailing slash for routes that represent single items or actions.

Summary

Trailing slash in Flask routes controls URL redirection and 404 errors.

Routes with trailing slash redirect URLs without it to the slash version.

Routes without trailing slash do not accept URLs with an extra slash.