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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 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.