python 47 lines · 6 steps

Serializing SQLAlchemy models in Flask JSON

A custom JSON provider teaches Flask how to serialize ORM models and other unsupported types automatically.

Explained by highlit
1from datetime import datetime, date
2from decimal import Decimal
3from flask import Flask, jsonify
4from flask.json.provider import DefaultJSONProvider
5from sqlalchemy.orm import DeclarativeBase
6from sqlalchemy.inspection import inspect
7 
8 
9class Base(DeclarativeBase):
10 def to_dict(self, exclude=()):
11 columns = inspect(self).mapper.column_attrs
12 return {
13 attr.key: getattr(self, attr.key)
14 for attr in columns
15 if attr.key not in exclude
16 }
17 
18 
19class ModelJSONProvider(DefaultJSONProvider):
20 def default(self, obj):
21 if isinstance(obj, Base):
22 return obj.to_dict()
23 if isinstance(obj, (datetime, date)):
24 return obj.isoformat()
25 if isinstance(obj, Decimal):
26 return float(obj)
27 if isinstance(obj, set):
28 return list(obj)
29 return super().default(obj)
30 
31 
32app = Flask(__name__)
33app.json = ModelJSONProvider(app)
34 
35 
36@app.get("/users/<int:user_id>")
37def get_user(user_id):
38 user = db.session.get(User, user_id)
39 if user is None:
40 return jsonify(error="user not found"), 404
41 return jsonify(user)
42 
43 
44@app.get("/users")
45def list_users():
46 users = db.session.scalars(db.select(User).order_by(User.created_at)).all()
47 return jsonify(users=users, count=len(users))
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A custom JSONProvider centralizes serialization so routes can return raw model objects.
  2. 2Overriding default() lets you handle each unsupported type in one predictable place.
  3. 3SQLAlchemy inspection turns a model's mapped columns into a plain dict generically.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Serializing SQLAlchemy models in Flask JSON — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code