How to Use This Quick Reference
This page is organized as a scannable cheat sheet rather than a tutorial: each section groups closely related Flask APIs (routing, request/response, context, CLI) so you can jump straight to the syntax you half-remember instead of re-reading full explanations, which is exactly the kind of lookup you need mid-coding rather than while first learning the concept.
Cricket analogy: A batter glances at a laminated card of field placements taped to the dressing room wall for a quick reminder rather than rereading a full coaching manual mid-innings, the same fast-lookup purpose this cheat sheet serves.
Routing and Views Cheat Sheet
Routes are registered with @app.route('/path', methods=['GET', 'POST']), URL converters like <int:id>, <string:slug>, or <path:subpath> constrain and type-convert dynamic segments, and url_for('endpoint_name', id=5) generates URLs by endpoint name rather than hardcoded strings so routes can change without breaking every link. Blueprints register their own routes with @bp.route(...) and are mounted onto the app via app.register_blueprint(bp, url_prefix='/api').
Cricket analogy: A scoreboard operator uses a standard coded system (like '4' or '6' for boundaries) rather than free-text descriptions, similar to how URL converters like <int:id> constrain and standardize what a route segment can accept.
Request, Response, and Context Cheat Sheet
Inside a view, request.args gets query string parameters, request.form gets submitted form fields, request.get_json() parses a JSON body, and request.files handles uploads. For responses, return a string for a simple 200 OK, return a tuple (body, status_code) or (body, status_code, headers) for custom status/headers, jsonify(data) for JSON responses with the correct Content-Type, and abort(404) to short-circuit with an HTTP error.
Cricket analogy: An umpire reads different signals depending on the situation — a raised finger for out, crossed arms for a dead ball, arms out for a wide — each a distinct, purpose-built signal, similar to request.args, request.form, and request.get_json() each reading a different part of the request.
CLI and Configuration Cheat Sheet
flask run starts the dev server (reads FLASK_APP and FLASK_DEBUG from environment or a .flaskenv file), flask shell opens a Python shell with the app context already pushed, and flask db migrate / flask db upgrade run Flask-Migrate/Alembic database migrations. Custom commands are defined with @app.cli.command('seed') and become available as flask seed once the app factory registers them.
Cricket analogy: A team has a standard set of pre-match rituals — toss, warm-up, national anthem — each triggered by a known cue, similar to how flask run, flask shell, and flask db upgrade are standard, named commands with predictable behavior.
from flask import Flask, request, jsonify, abort, url_for
app = Flask(__name__)
@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
user = db.session.get(User, user_id)
if user is None:
abort(404)
return jsonify({"id": user.id, "name": user.name})
@app.route("/users", methods=["POST"])
def create_user():
data = request.get_json()
name = data.get("name")
if not name:
return jsonify({"error": "name is required"}), 400
user = User(name=name)
db.session.add(user)
db.session.commit()
return jsonify({"id": user.id, "url": url_for("get_user", user_id=user.id)}), 201
@app.cli.command("seed")
def seed():
"""Usage: flask seed"""
db.session.add(User(name="Demo User"))
db.session.commit()
print("Seeded database.")
Set FLASK_APP=myapp and FLASK_DEBUG=1 in a .flaskenv file (loaded automatically if python-dotenv is installed) so you don't have to export them manually in every terminal session during local development.
- @app.route() with URL converters like <int:id> defines and type-constrains dynamic route segments.
- url_for('endpoint_name') generates URLs by endpoint name so routes can change without breaking links.
- request.args, request.form, request.get_json(), and request.files each read a distinct part of a request.
- jsonify(), tuples like (body, status), and abort(404) are the standard ways to shape a response.
- Blueprints are mounted with app.register_blueprint(bp, url_prefix='/api') to modularize routes.
- flask run, flask shell, and flask db migrate/upgrade are the core built-in CLI commands.
- @app.cli.command('name') registers a custom command runnable as flask name.
Practice what you learned
1. What does the URL converter in @app.route('/users/<int:user_id>') do?
2. Why is url_for('endpoint_name') preferred over hardcoding a URL string like '/users/5'?
3. Which request attribute would you use to parse a JSON body sent in a POST request?
4. What does flask shell do?
5. How do you register a custom Flask CLI command that can be run as 'flask seed'?
Was this page helpful?
You May Also Like
Flask Interview Questions
A curated set of common Flask interview questions covering core concepts, application structure, and debugging, with explanations to help you prepare.
Testing Flask Applications
Learn how to write reliable unit and integration tests for Flask apps using pytest, the Flask test client, and fixtures for database and app context.
Flask with Gunicorn and WSGI
Understand the WSGI standard that powers Flask and how to run Flask applications in production using Gunicorn as an application server.
Deploying a Flask App
A practical guide to taking a Flask application from local development to a secure, production deployment using Docker, environment configuration, and health checks.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics