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
import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry
Building a resilient requests Session
retries
backoff
http-client
Intermediate
7 steps
php
<?php function uploadDocument(string $endpoint, string $filePath, array $meta): array {
Uploading a file with cURL in PHP
curl
file-upload
http
Intermediate
8 steps
python
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, ConfigDict, EmailStr from sqlalchemy.orm import Session
Building a users router in FastAPI
routing
serialization
dependency-injection
Intermediate
7 steps
python
import json from dataclasses import dataclass, field, asdict from datetime import datetime from typing import Any
JSON round-tripping with Python dataclasses
dataclasses
serialization
json
Intermediate
6 steps
rust
use std::fs::File; use std::io::{self, BufWriter}; use std::path::Path;
Serializing config to JSON in Rust
serialization
serde
file-io
Intermediate
7 steps
python
import re from django.core.exceptions import ValidationError from django.core.validators import RegexValidator
Building a deconstructible validator in Django
validation
regex
deconstructible
Intermediate
7 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.