Clean, predictable URLs are the public interface of a web app.
Routes can contain variables in angle brackets. The value is passed to your view as a keyword argument:
@app.route("/users/<username>")
def profile(username): ...A converter checks and converts the value: <int:post_id>, <float:x>, <path:subpath> (accepts slashes), <uuid:id>, and the default string, which accepts anything without a slash. If the URL doesn't match a converter, for example /posts/abc for an int, Flask returns 404 without calling your function.
By default a route answers only GET (and HEAD and OPTIONS automatically). Allow others with methods=["GET", "POST"] and branch on request.method, or use the shortcuts @app.get, @app.post, @app.put, @app.patch and @app.delete, one view per method. A request with a method the route doesn't allow gets 405 Method Not Allowed.
Trailing slashes follow a filesystem analogy:
/projects/(with slash) is like a folder: visiting/projectsredirects to/projects/./about(without slash) is like a file:/about/is a 404.
This keeps URLs unique, which search engines like. Pick one style per resource and stick to it.
Each route has an endpoint name, by default the function name. Endpoint names, not paths, are what you use to build URLs with url_for, so two views cannot share a function name.
Example
from flask import Flask
app = Flask(__name__)
@app.get("/posts/<int:post_id>")
def show_post(post_id):
return f"post {post_id} ({type(post_id).__name__})"
@app.post("/posts")
def create_post():
return "created", 201
@app.route("/projects/")
def projects():
return "projects"
c = app.test_client()
print(c.get("/posts/42").text) # post 42 (int)
print(c.get("/posts/abc").status_code) # 404
print(c.delete("/posts/42").status_code) # 405
print(c.post("/posts").status_code) # 201
print(c.get("/projects").status_code) # 308 (redirect to /projects/)Remember
- <converter:name> captures and converts URL parts; mismatches are 404s
- Use methods=[...] or @app.get/@app.post to choose HTTP methods
- A route ending in / redirects the slashless URL; the reverse is a 404
Watch out for
- Defining two view functions with the same name, which gives two routes the same endpoint and fails at startup.