Flask API Reference & Cheatsheet
Flask is a lightweight Python web framework that gives you the essentials — routing, request handling, templates — without dictating how to structure your application. This reference covers the patterns you’ll use daily.
What’s in This Reference
- Basic application setup and route patterns
- Request and response handling (GET/POST, JSON, headers, cookies)
- Jinja2 template engine syntax
- SQLAlchemy database integration
- Blueprints for modular application structure
- Error handlers and form handling
- Deployment with Gunicorn
flowchart TD
A["Request"] --> B["Route Matcher"]
B --> C["View Function"]
C --> D{"Template?"}
D -->|"Yes"| E["Render Template"]
D -->|"No"| F["Return Response"]
E --> F
F --> G["Client"]
style A fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
style B fill:#fef3c7,stroke:#f59e0b,color:#78350f
style C fill:#d1fae5,stroke:#10b981,color:#064e3b
style F fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
Basic Application
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Hello, Flask!</h1>"
if __name__ == "__main__":
app.run(debug=True)Route Patterns
@app.route("/user/<username>")
def show_user(username):
return f"User: {username}"
@app.route("/post/<int:post_id>")
def show_post(post_id):
return f"Post: {post_id}"
@app.route("/path/<path:subpath>")
def show_subpath(subpath):
return f"Subpath: {subpath}"
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form["username"]
return f"Logged in as {username}!"
return render_template("login.html")Route converters: string (default), int, float, path (accepts slashes), uuid.
Request and Response
from flask import request, jsonify, make_response
# Access request data
request.args # GET parameters (dict-like)
request.form # POST form data (dict-like)
request.json # JSON request body (parsed)
request.headers # HTTP headers
request.cookies # Cookies
request.method # HTTP method (GET, POST, etc.)
request.files # Uploaded files
# JSON response
@app.route("/api/data")
def api():
return jsonify({"key": "value", "count": 42})
# Custom response with headers and status
@app.route("/custom")
def custom():
response = make_response("Custom response", 201)
response.headers["X-Custom"] = "value"
response.set_cookie("session", "abc123")
return responseJinja2 Templates
{# Variables #}
<h1>{{ title }}</h1>
<p>{{ description }}</p>
{# Filters #}
{{ name|upper }}
{{ text|truncate(100) }}
{{ price|round(2) }}
{{ date|format_datetime }}
{# Control flow #}
{% if user.is_authenticated %}
<p>Welcome, {{ user.name }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
{% for product in products %}
<div class="product">
<h3>{{ product.name }}</h3>
<p>${{ product.price }}</p>
</div>
{% endfor %}
{# Template inheritance #}
{% extends "base.html" %}
{% block content %}
{# Page-specific content #}
{% endblock %}
{# Include partials #}
{% include "header.html" %}
{# URL generation #}
<a href="{{ url_for('show_post', post_id=5) }}">View Post</a>SQLAlchemy Integration
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
posts = db.relationship("Post", backref="author", lazy=True)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
body = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
# Usage in routes
@app.route("/users")
def list_users():
users = User.query.all()
return render_template("users.html", users=users)
@app.route("/users/<username>")
def user_profile(username):
user = User.query.filter_by(username=username).first_or_404()
return render_template("profile.html", user=user)
# Create and save
new_user = User(username="Alice", email="alice@example.com")
db.session.add(new_user)
db.session.commit()
# Query with filters
User.query.filter(User.email.endswith("@example.com")).all()
User.query.order_by(User.created_at.desc()).limit(10).all()
Post.query.filter(Post.title.contains("Python")).all()Blueprints
Blueprints let you organize your application into modules:
# auth.py
from flask import Blueprint, render_template
auth = Blueprint("auth", __name__, url_prefix="/auth")
@auth.route("/login")
def login():
return render_template("auth/login.html")
@auth.route("/register")
def register():
return render_template("auth/register.html")
@auth.route("/logout")
def logout():
return "Logged out"
# main.py — register the blueprint
from auth import auth
app.register_blueprint(auth)
# Now /auth/login, /auth/register, /auth/logout are availableError Handlers
from flask import jsonify
@app.errorhandler(404)
def not_found(error):
return jsonify({"error": "Not found", "status": 404}), 404
@app.errorhandler(500)
def server_error(error):
return jsonify({"error": "Internal server error"}), 500
@app.errorhandler(403)
def forbidden(error):
return render_template("errors/403.html"), 403Form Handling
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
class LoginForm(FlaskForm):
username = StringField("Username", validators=[DataRequired()])
password = PasswordField("Password", validators=[DataRequired()])
submit = SubmitField("Log In")
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
username = form.username.data
return f"Welcome, {username}!"
return render_template("login.html", form=form)Session and Flash Messages
from flask import session, flash, redirect
app.secret_key = "your-secret-key-here"
@app.route("/login", methods=["POST"])
def login():
session["user_id"] = user.id
session["username"] = user.username
flash("Logged in successfully!", "success")
return redirect(url_for("dashboard"))
@app.route("/logout")
def logout():
session.clear()
flash("Logged out.", "info")
return redirect(url_for("home"))Common Mistakes
1. Forgetting app.secret_key
Sessions and flash messages require a secret key. Always set app.secret_key to a random string.
2. Not Using request.method Check
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
# handle form submission
else:
# show form3. Forgetting to Create Database Tables
After defining models, create tables in the Flask shell or with db.create_all().
4. Leaving Debug Mode On in Production
Set debug=True only during development. In production, use Gunicorn with debug=False.
FAQ
Try It Yourself
Save this as app.py and run it:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Hello, Flask!</h1>"
@app.route("/about")
def about():
return "<h1>About Flask</h1><p>Flask is a micro web framework.</p>"
if __name__ == "__main__":
app.run(debug=True)Run python app.py and visit http://localhost:5000. You should see “Hello, Flask!”.
Deployment
# Install Gunicorn
pip install gunicorn
# Run with 4 workers
gunicorn -w 4 -b 0.0.0.0:8000 app:app
# With Nginx reverse proxy (recommended for production)
# nginx.conf snippet:
# location / {
# proxy_pass http://127.0.0.1:8000;
# proxy_set_header Host $host;
# }What’s Next
| Topic | Description | Link |
|---|---|---|
| Django Reference | Compare with full-stack Django | https://tutorials.dodatech.com/programming-languages/python/django/reference/ |
| FastAPI Reference | Compare with async FastAPI | https://tutorials.dodatech.com/programming-languages/python/fastapi/reference/ |
| Python Basics | Review core Python concepts | https://tutorials.dodatech.com/programming-languages/python/py-basics/ |
| SQLAlchemy | Flask’s ORM documentation | SQLAlchemy |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro