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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A custom JSONProvider centralizes serialization so routes can return raw model objects.
- 2Overriding default() lets you handle each unsupported type in one predictable place.
- 3SQLAlchemy inspection turns a model's mapped columns into a plain dict generically.
Related explainers
python
from itertools import cycle from collections import defaultdict
Round-robin task distribution in Python
round-robin
iterators
load-balancing
Intermediate
6 steps
python
import base64 import json from typing import Annotated, Optional
Cursor pagination in a FastAPI endpoint
pagination
cursor
async
Intermediate
9 steps
python
import secrets from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import APIKeyHeader
API key authentication as a FastAPI dependency
authentication
dependency-injection
api-keys
Intermediate
8 steps
python
import hashlib from collections import defaultdict from pathlib import Path
Finding duplicate files by size then hash
hashing
file-io
deduplication
Intermediate
7 steps
python
from flask import Flask, request, g, jsonify from flask_babel import Babel, gettext as _, format_datetime from datetime import datetime
Per-request localization in Flask with Babel
i18n
content-negotiation
request-lifecycle
Intermediate
8 steps
python
from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save, post_delete from django.dispatch import receiver
Busting template fragment caches in Django
caching
signals
cache-invalidation
Intermediate
4 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/serializing-sqlalchemy-models-in-flask-json-explained-python-8b01/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.