Python Flask: Building REST APIs
Most Flask APIs start as a single app.py with five routes and a list of dicts pretending to be a database. Then someone needs login, a real table, and tests, and that file turns into 800 lines nobody wants to touch. The framework isn't the problem. The structure is.
This post walks through building a Flask REST API the way I'd set it up if I knew it would grow: an application factory, blueprints, SQLAlchemy models, JWT auth with refresh tokens, JSON error handlers, and a pytest suite that runs without a server.
Flask gives you routing, request parsing and a test client, and leaves the rest to you. That's a good fit for small services and internal APIs where you want to pick your own ORM, validation and auth libraries instead of inheriting a full framework's opinions.
What Flask Actually Gives You
"Micro" doesn't mean feature-poor. Flask keeps a small, stable core (it's a WSGI app) and pushes everything else out to extensions. Under the hood it sits on two libraries:
- Werkzeug: The WSGI toolkit that handles request/response objects, URL routing, and HTTP utilities
- Jinja2: A fast templating engine (used for HTML responses, though less relevant for pure JSON APIs)
When your client sends an HTTP request, Flask's Werkzeug layer parses it into a Request object, the URL dispatcher finds the matching view function, and that function returns a Response. For an API, that's usually whatever you passed to jsonify(). The full flow:
Flask request/response lifecycle
Flask vs Django vs FastAPI
If you're still picking a framework, here's the rough shape of the three common choices:
| Feature | Flask | Django | FastAPI |
|---|---|---|---|
| Philosophy | Micro-framework, flexible | Batteries included | Async-first, type hints |
| Learning curve | Low | Medium to High | Low to Medium |
| Performance | Good (sync) | Good (sync) | Strong for I/O-bound async work |
| Auto docs | Via extensions | Via DRF | Built-in (OpenAPI) |
| Best for | Microservices, quick APIs | Full-stack web apps | High-throughput async APIs |
| ORM | SQLAlchemy (extension) | Built-in Django ORM | SQLAlchemy / Tortoise |
Installation and Project Setup
Put every Flask project in its own virtual environment, or sooner or later two projects will fight over package versions. The setup is four steps:
Create a virtual environment
Python ships with venv, so there's nothing extra to install. This keeps your project's packages isolated from the system Python.
Install Flask and core extensions
Install Flask along with flask-sqlalchemy for database access, flask-jwt-extended for authentication, and marshmallow for serialization.
Scaffold the project structure
Organise code into an app/ package with blueprints for each domain area (users, auth, products, etc.).
Set up environment config
Store secrets in a .env file and load them with python-dotenv. Never hard-code database URLs or secret keys.
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install dependencies
pip install flask flask-sqlalchemy flask-jwt-extended \
flask-migrate marshmallow python-dotenv pytest
# Freeze versions
pip freeze > requirements.txt
# Project layout
my-api/
├── app/
│ ├── __init__.py # Application factory
│ ├── config.py # Configuration classes
│ ├── models.py # SQLAlchemy models
│ ├── auth/
│ │ ├── __init__.py
│ │ └── routes.py # /auth blueprint
│ └── users/
│ ├── __init__.py
│ └── routes.py # /users blueprint
├── tests/
│ └── test_users.py
├── .env
└── run.py
Routing and HTTP Methods
The @app.route() decorator maps a URL pattern to a function. Each route lists the HTTP methods it accepts. Leave out methods and Flask only allows GET (plus HEAD and OPTIONS, which it adds for you).
Return a list or single resource as JSON:
from flask import Flask, jsonify
app = Flask(__name__)
users = [
{"id": 1, "name": "Alice", "email": "alice@example.com"},
{"id": 2, "name": "Bob", "email": "bob@example.com"},
]
@app.route("/users", methods=["GET"])
def get_users():
return jsonify(users), 200
@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
user = next((u for u in users if u["id"] == user_id), None)
if user is None:
return jsonify({"error": "User not found"}), 404
return jsonify(user), 200
Accept JSON body data to create a resource:
from flask import request
@app.route("/users", methods=["POST"])
def create_user():
data = request.get_json()
# Basic validation
if not data or "name" not in data or "email" not in data:
return jsonify({"error": "name and email are required"}), 400
new_user = {
"id": len(users) + 1,
"name": data["name"],
"email": data["email"],
}
users.append(new_user)
return jsonify(new_user), 201
One gotcha: since Flask 2.1, request.get_json() raises an error if the request's Content-Type isn't application/json, and the client gets a 415 Unsupported Media Type back. If curl calls "randomly" fail, check that you passed -H "Content-Type: application/json". Use request.get_json(silent=True) if you'd rather get None and return your own 400.
Update or delete an existing resource:
@app.route("/users/<int:user_id>", methods=["PUT"])
def update_user(user_id):
data = request.get_json()
user = next((u for u in users if u["id"] == user_id), None)
if user is None:
return jsonify({"error": "User not found"}), 404
user.update({k: v for k, v in data.items() if k in ("name", "email")})
return jsonify(user), 200
@app.route("/users/<int:user_id>", methods=["DELETE"])
def delete_user(user_id):
global users
users = [u for u in users if u["id"] != user_id]
return "", 204 # 204 No Content: standard delete response
Flask URL converters let you type-check path segments automatically:
# int converter: returns 404 if segment is not an integer
@app.route("/posts/<int:post_id>")
def get_post(post_id): ...
# string converter (default): matches any non-slash text
@app.route("/users/<string:username>")
def get_by_username(username): ...
# path converter: matches slashes too (useful for file paths)
@app.route("/files/<path:filepath>")
def get_file(filepath): ...
# Multiple segments
@app.route("/users/<int:user_id>/posts/<int:post_id>")
def get_user_post(user_id, post_id): ...
Blueprints and the Application Factory
Once you're past a handful of routes, one app.py gets painful. Blueprints let you split routes into modules by domain, and the application factory pattern means you can build a fresh app per test or per environment instead of importing one global object.
Flask Blueprint architecture: each domain owns its routes
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_migrate import Migrate
db = SQLAlchemy()
jwt = JWTManager()
migrate = Migrate()
def create_app(config_name="development"):
app = Flask(__name__)
# Load config
from app.config import config_map
app.config.from_object(config_map[config_name])
# Initialise extensions
db.init_app(app)
jwt.init_app(app)
migrate.init_app(app, db)
# Register blueprints
from app.auth.routes import auth_bp
from app.users.routes import users_bp
app.register_blueprint(auth_bp, url_prefix="/auth")
app.register_blueprint(users_bp, url_prefix="/users")
return app
import os
from dotenv import load_dotenv
load_dotenv()
class BaseConfig:
SECRET_KEY = os.getenv("SECRET_KEY", "change-me")
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "change-me-jwt")
SQLALCHEMY_TRACK_MODIFICATIONS = False
class DevelopmentConfig(BaseConfig):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.getenv(
"DATABASE_URL", "sqlite:///dev.db"
)
class ProductionConfig(BaseConfig):
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URL")
config_map = {
"development": DevelopmentConfig,
"production": ProductionConfig,
}
Database Integration with SQLAlchemy
Flask-SQLAlchemy wires SQLAlchemy into the app context and gives you a session per request. You define models as Python classes and SQLAlchemy maps them to tables. Swapping SQLite in development for PostgreSQL or MySQL in production is mostly a matter of changing DATABASE_URL, though you'll still want to run your tests against the real database before you trust that.
Defining Models
from datetime import datetime
from app import db
class User(db.Model):
__tablename__ = "users"
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)
password = db.Column(db.String(256), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# One-to-many: a user can have many posts
posts = db.relationship("Post", back_populates="author",
lazy="dynamic", cascade="all, delete")
def to_dict(self):
return {
"id": self.id,
"username": self.username,
"email": self.email,
"created_at": self.created_at.isoformat(),
}
class Post(db.Model):
__tablename__ = "posts"
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("users.id"), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
author = db.relationship("User", back_populates="posts")
CRUD Operations
from flask import Blueprint, jsonify, request
from app import db
from app.models import User
users_bp = Blueprint("users", __name__)
@users_bp.route("/", methods=["GET"])
def list_users():
page = request.args.get("page", 1, type=int)
limit = request.args.get("limit", 20, type=int)
pagination = User.query.order_by(User.created_at.desc()) \
.paginate(page=page, per_page=limit, error_out=False)
return jsonify({
"users": [u.to_dict() for u in pagination.items],
"total": pagination.total,
"page": pagination.page,
"pages": pagination.pages,
}), 200
@users_bp.route("/<int:user_id>", methods=["GET"])
def get_user(user_id):
user = User.query.get_or_404(user_id)
return jsonify(user.to_dict()), 200
@users_bp.route("/<int:user_id>", methods=["PUT"])
def update_user(user_id):
user = User.query.get_or_404(user_id)
data = request.get_json()
if "username" in data:
user.username = data["username"]
if "email" in data:
user.email = data["email"]
db.session.commit()
return jsonify(user.to_dict()), 200
@users_bp.route("/<int:user_id>", methods=["DELETE"])
def delete_user(user_id):
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return "", 204
The ORM parameterizes queries for you, so User.query.filter_by(email=email).first() is safe from SQL injection. The risk comes back the moment you build raw SQL with f-strings and pass it to db.session.execute(). If you need raw SQL, use text() with bound parameters.
JWT Authentication
For a stateless API, JWTs are the usual choice, and Flask-JWT-Extended handles issuing and verifying them. The flow: the client posts credentials to /auth/login, receives an access token (short-lived) and a refresh token (long-lived), then sends the access token as a Bearer header on every protected request.
from flask import Blueprint, jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import (
create_access_token, create_refresh_token,
jwt_required, get_jwt_identity,
)
from app import db
from app.models import User
auth_bp = Blueprint("auth", __name__)
@auth_bp.route("/register", methods=["POST"])
def register():
data = request.get_json() or {}
if not data.get("username") or not data.get("email") or not data.get("password"):
return jsonify({"error": "username, email and password required"}), 400
if User.query.filter_by(email=data["email"]).first():
return jsonify({"error": "Email already registered"}), 409
user = User(
username = data["username"],
email = data["email"],
password = generate_password_hash(data["password"]),
)
db.session.add(user)
db.session.commit()
return jsonify(user.to_dict()), 201
@auth_bp.route("/login", methods=["POST"])
def login():
data = request.get_json() or {}
user = User.query.filter_by(email=data.get("email")).first()
if not user or not check_password_hash(user.password, data.get("password", "")):
return jsonify({"error": "Invalid credentials"}), 401
access_token = create_access_token(identity=user.id)
refresh_token = create_refresh_token(identity=user.id)
return jsonify({"access_token": access_token,
"refresh_token": refresh_token}), 200
@auth_bp.route("/refresh", methods=["POST"])
@jwt_required(refresh=True)
def refresh():
identity = get_jwt_identity()
access_token = create_access_token(identity=identity)
return jsonify({"access_token": access_token}), 200
@auth_bp.route("/me", methods=["GET"])
@jwt_required()
def me():
user_id = get_jwt_identity()
user = User.query.get_or_404(user_id)
return jsonify(user.to_dict()), 200
With recent versions (Flask-JWT-Extended 4.7+ on PyJWT 2.10+), passing an integer like identity=user.id produces tokens that fail verification: protected routes answer 422 with {"msg": "Subject must be a string"}. Use identity=str(user.id) when creating tokens and convert back with int(get_jwt_identity()) where you need the number.
To protect a route, add @jwt_required(). Requests with a missing or expired token get rejected before your function runs:
from flask_jwt_extended import jwt_required, get_jwt_identity
@users_bp.route("/profile", methods=["GET"])
@jwt_required() # returns 401 if token missing or expired
def my_profile():
user_id = get_jwt_identity()
user = User.query.get_or_404(user_id)
return jsonify(user.to_dict()), 200
# Client sends:
# Authorization: Bearer <access_token>
Error Handling and Response Formatting
Out of the box, Flask answers a 404 or 500 with an HTML page, which is the last thing a JavaScript client wants to parse. Register global error handlers so every error (404, 422, 500) comes back in the same JSON shape.
from flask import jsonify
from werkzeug.exceptions import HTTPException
def register_error_handlers(app):
@app.errorhandler(HTTPException)
def http_error(e):
return jsonify({
"error": e.name,
"message": e.description,
"status": e.code,
}), e.code
@app.errorhandler(Exception)
def unhandled_error(e):
app.logger.error("Unhandled exception: %s", str(e))
return jsonify({
"error": "Internal Server Error",
"message": "An unexpected error occurred.",
"status": 500,
}), 500
# In create_app():
# register_error_handlers(app)
Call abort() anywhere in a view and the matching handler takes over:
from flask import abort
@users_bp.route("/<int:user_id>", methods=["GET"])
def get_user(user_id):
user = User.query.get(user_id)
if user is None:
abort(404, description=f"User {user_id} not found")
return jsonify(user.to_dict()), 200
# Response:
# {
# "error": "Not Found",
# "message": "User 42 not found",
# "status": 404
# }
Common HTTP Status Codes Quick Reference
| Code | Meaning | When to use |
|---|---|---|
| 200 OK | Success | GET, PUT returning updated resource |
| 201 Created | Resource created | Successful POST |
| 204 No Content | Success, no body | Successful DELETE |
| 400 Bad Request | Invalid input | Missing required fields, validation failure |
| 401 Unauthorized | Not authenticated | Missing / invalid token |
| 403 Forbidden | Not authorized | Authenticated but insufficient permissions |
| 404 Not Found | Resource missing | ID doesn't exist in database |
| 409 Conflict | Duplicate resource | Email already registered |
| 422 Unprocessable | Semantic error | Structurally valid JSON but fails business rules |
| 500 Server Error | Unexpected failure | Unhandled exception (never expose details) |
Testing Flask APIs
Flask's test client sends requests to your app in memory, so there's no server to start. Pair it with pytest and an in-memory SQLite database and the whole suite runs in seconds. Note that the fixture below calls create_app("testing"), so add a "testing" entry to config_map first or you'll get a KeyError before a single test runs.
import pytest
from app import create_app, db as _db
@pytest.fixture(scope="session")
def app():
app = create_app("testing")
app.config.update({
"TESTING": True,
"SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:",
})
with app.app_context():
_db.create_all()
yield app
_db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture(autouse=True)
def clean_db(app):
yield
with app.app_context():
for table in reversed(_db.metadata.sorted_tables):
_db.session.execute(table.delete())
_db.session.commit()
def test_register_success(client):
res = client.post("/auth/register", json={
"username": "alice",
"email": "alice@example.com",
"password": "securepass123",
})
assert res.status_code == 201
data = res.get_json()
assert data["email"] == "alice@example.com"
assert "password" not in data # never leak hashed password
def test_register_duplicate_email(client):
payload = {"username": "bob", "email": "bob@test.com", "password": "pass"}
client.post("/auth/register", json=payload)
res = client.post("/auth/register", json=payload)
assert res.status_code == 409
def test_login_returns_tokens(client):
client.post("/auth/register", json={
"username": "carol", "email": "carol@test.com", "password": "mypassword"
})
res = client.post("/auth/login", json={
"email": "carol@test.com", "password": "mypassword"
})
assert res.status_code == 200
data = res.get_json()
assert "access_token" in data
assert "refresh_token" in data
def test_protected_route_without_token(client):
res = client.get("/auth/me")
assert res.status_code == 401
Run the full test suite with pytest -v. Use pytest --cov=app (requires pytest-cov) to see coverage reports. Don't chase a number; make sure every route has at least a happy-path test and one for the error it's most likely to return.
Deployment Checklist
Before a Flask API goes live, I go through this list:
- Use Gunicorn or uWSGI as the WSGI server, never
flask run. Example:gunicorn -w 4 "app:create_app()" - Set
DEBUG = False. The interactive debugger lets anyone who triggers an error run arbitrary Python on your server. - Replace the default secrets. The config above falls back to
"change-me", which is fine locally and a disaster in production. Generate real values withpython -c "import secrets; print(secrets.token_hex(32))". - Run migrations, don't call
create_all(). With Flask-Migrate:flask db init, thenflask db migrate -m "initial", thenflask db upgrade. - Put Nginx in front of Gunicorn for TLS termination, rate limiting and static files.
- Keep credentials out of git. Use environment variables or a secrets manager, and add
.envto.gitignore. - Configure CORS explicitly with
flask-cors:CORS(app, origins=["https://yourdomain.com"]). Avoid the wildcard default if the API uses cookies or auth headers.
When I'd Use Flask (and When I Wouldn't)
Flask is a good pick for small to medium JSON APIs, internal services, and anything that wraps existing Python code (a model, a scraper, a data pipeline) behind HTTP. You choose your own pieces, the request flow is easy to follow, and there's very little framework to fight.
That freedom has a cost. Validation, serialization, OpenAPI docs, permissions and admin screens are all things you assemble yourself, and on a bigger team everyone assembles them slightly differently. If you need an admin panel and a lot of CRUD, Django with DRF gets you there faster. If the API spends most of its time waiting on other services or needs request validation and docs generated from type hints, FastAPI is the better fit. And if you're already running Laravel or Node for everything else, adding a Python service only makes sense when you actually need a Python library.
If you do go with Flask, the things worth adding next are Flask-Limiter for rate limiting your login route, Celery or RQ for anything that shouldn't block a request, and a schema library (marshmallow or pydantic) so validation isn't hand-written if checks in every view.