Flask Cheatsheet

Routing

Use this Flask reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Basic Routes

Flask routing is a practical first backend concept for coding beginners: one URL maps to one Python function, then the app returns HTML, text, or JSON.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def index():
    return "Home"

@app.route("/about")
def about():
    return "About"

URL Variables (Converters)

@app.route("/user/<username>")
def user_profile(username):
    return f"User: {username}"

@app.route("/post/<int:post_id>")
def show_post(post_id):          # post_id is an int
    return f"Post {post_id}"

@app.route("/price/<float:amount>")
def price(amount):
    return f"${amount:.2f}"

@app.route("/path/<path:subpath>")
def show_path(subpath):          # matches slashes too
    return f"Path: {subpath}"

@app.route("/uuid/<uuid:uid>")
def by_uuid(uid):                # uid is a uuid.UUID object
    return str(uid)

Converter Quick Reference

ConverterPython TypeMatches
stringstrAny text without a slash (default)
intintPositive integers
floatfloatPositive floating-point numbers
pathstrLike string but also accepts /
uuiduuid.UUIDUUID strings

Custom converter:

from werkzeug.routing import BaseConverter

class ListConverter(BaseConverter):
    def to_python(self, value):
        return value.split("+")
    def to_url(self, values):
        return "+".join(super().to_url(v) for v in values)

app.url_map.converters["list"] = ListConverter

@app.route("/tags/<list:tags>")
def tags(tags):                  # /tags/python+flask → ["python", "flask"]
    return str(tags)

HTTP Methods

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

Method-specific shortcuts (Flask 2+):

@app.get("/items")
def list_items(): ...

@app.post("/items")
def create_item(): ...

@app.put("/items/<int:id>")
def update_item(id): ...

@app.patch("/items/<int:id>")
def patch_item(id): ...

@app.delete("/items/<int:id>")
def delete_item(id): ...

URL Building with url_for

from flask import url_for

with app.test_request_context():
    url_for("index")                      # "/"
    url_for("user_profile", username="bob")  # "/user/bob"
    url_for("static", filename="style.css")  # "/static/style.css"
    url_for("user_profile", username="bob", _external=True)
    # "http://localhost/user/bob"
    url_for("search", q="flask", page=2)  # "/search?q=flask&page=2"
    url_for("api.items", _scheme="https", _external=True)

Always use url_for instead of hardcoding paths — it respects APPLICATION_ROOT and SERVER_NAME, and handles encoding.

Trailing Slashes

@app.route("/projects/")   # canonical URL has trailing slash
def projects():            # /projects redirects → /projects/
    ...

@app.route("/about")       # no trailing slash
def about():               # /about/ returns 404
    ...

Redirects and Strict Slashes

app = Flask(__name__)
app.url_map.strict_slashes = False   # disables 301 redirect for all routes

# Per-route override:
@app.route("/noslash", strict_slashes=False)
def noslash():
    return "ok"

Static Files

# Served from /static/ by default; override:
app = Flask(__name__, static_url_path="/assets", static_folder="public")

# URL to a static file:
url_for("static", filename="js/app.js")

add_url_rule (Programmatic)

def hello():
    return "Hello"

app.add_url_rule(
    "/hello",
    endpoint="hello",    # defaults to function name
    view_func=hello,
    methods=["GET"],
)

Class-Based Views

from flask.views import MethodView

class ItemAPI(MethodView):
    def get(self, item_id=None):
        if item_id is None:
            return "list all"
        return f"item {item_id}"

    def post(self):
        return "create", 201

    def put(self, item_id):
        return f"update {item_id}"

    def delete(self, item_id):
        return f"delete {item_id}", 204

view = ItemAPI.as_view("item_api")
app.add_url_rule("/items/", view_func=view, methods=["GET", "POST"])
app.add_url_rule("/items/<int:item_id>", view_func=view,
                 methods=["GET", "PUT", "DELETE"])

URL Map Inspection

# Print all registered routes
with app.app_context():
    print(app.url_map)

# Via CLI
flask routes

Before / After Request Hooks

@app.before_request
def load_user():
    g.user = get_current_user()

@app.after_request
def add_header(response):
    response.headers["X-Frame-Options"] = "DENY"
    return response

@app.teardown_request
def teardown(exception=None):
    db.session.remove()    # runs even if an exception occurred

Route Ordering and Gotchas

  • Flask matches routes in registration order for ambiguous patterns — more specific routes should be registered first or use more specific converters.
  • Variable rules never match an empty segment: /user/<name> does not match /user/.
  • url_for raises BuildError if the endpoint does not exist — always keep endpoint names in sync with function names or explicit endpoint= arguments.