Flask 3 cheatsheet

Flask 3: Routes and requests

10 common Flask 3 tasks.

Capture part of the URL

Convert the value to an integer with a converter.

@app.get("/users/<int:user_id>")
def show_user(user_id):
    return f"User {user_id}"

Handle several methods

Accept GET and POST on one route.

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        ...
    return render_template("login.html")

Read query string values

Read ?page=2 with a default.

page = request.args.get("page", 1, type=int)

Read a JSON body

Parse the JSON request body.

data = request.get_json()

Return JSON

Return a dict or list and Flask converts it to JSON, with a status code.

@app.post("/api/users")
def create_user():
    return {"id": 1, "name": "Ada"}, 201

Read form fields

Read submitted form values.

email = request.form["email"]

Redirect to another route

Send the user to another endpoint by name.

return redirect(url_for("index"))

Return an error

Stop the request with an HTTP error code.

from flask import abort

abort(404)

Customize an error page

Return a custom response for 404 errors.

@app.errorhandler(404)
def not_found(error):
    return render_template("404.html"), 404

Run code before every request

Run a function before each request, for example to load the current user.

@app.before_request
def load_user():
    g.user = get_user(session.get("user_id"))

Was this page helpful?