Backend Development

Python Flask: Building REST APIs

Mayur Dabhi
Mayur Dabhi
May 28, 2026
14 min read

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.

Why Flask?

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:

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:

Client Browser / App HTTP WSGI Server Gunicorn / uWSGI Flask App URL Dispatcher View Function jsonify(data) SQLAlchemy / JWT Marshmallow / etc. JSON resp HTTP Response

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:

1

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.

2

Install Flask and core extensions

Install Flask along with flask-sqlalchemy for database access, flask-jwt-extended for authentication, and marshmallow for serialization.

3

Scaffold the project structure

Organise code into an app/ package with blueprints for each domain area (users, auth, products, etc.).

4

Set up environment config

Store secrets in a .env file and load them with python-dotenv. Never hard-code database URLs or secret keys.

Terminal: project bootstrap
# 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.

create_app() Application Factory: app/__init__.py auth blueprint POST /auth/login POST /auth/register users blueprint GET /users GET /users/<id> products blueprint GET /products POST /products Shared: SQLAlchemy db · JWT manager · Migrate

Flask Blueprint architecture: each domain owns its routes

app/__init__.py: application factory
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
app/config.py
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

app/models.py
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

app/users/routes.py: CRUD with SQLAlchemy
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
Never Trust User Input

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.

app/auth/routes.py: register, login, refresh
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
"Subject must be a string"

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:

Protected endpoint example
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.

app/__init__.py: global error handlers
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:

Using abort() for clean error responses
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

CodeMeaningWhen to use
200 OKSuccessGET, PUT returning updated resource
201 CreatedResource createdSuccessful POST
204 No ContentSuccess, no bodySuccessful DELETE
400 Bad RequestInvalid inputMissing required fields, validation failure
401 UnauthorizedNot authenticatedMissing / invalid token
403 ForbiddenNot authorizedAuthenticated but insufficient permissions
404 Not FoundResource missingID doesn't exist in database
409 ConflictDuplicate resourceEmail already registered
422 UnprocessableSemantic errorStructurally valid JSON but fails business rules
500 Server ErrorUnexpected failureUnhandled 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.

tests/conftest.py: shared fixtures
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()
tests/test_auth.py: endpoint tests
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 Your Tests

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:

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.

Python Flask REST API SQLAlchemy JWT Backend
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.