Flask · Lesson 7 of 15
JSON APIs
Build a small JSON API with status codes, error handlers and marshmallow or pydantic.
- Intermediate
- 15 min read
- 3 objectives
Before this lessonLesson 6: Authentication with Flask-Login
What you will learn
- Return JSON
- Validate a body
- Map errors to status codes
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Flask can serve a JSON API. You do the validation and status codes yourself (or with marshmallow / pydantic). FastAPI automates more of this; Flask stays explicit.
JSON views
from flask import Blueprint, jsonify, request, abort
api = Blueprint("api", __name__, url_prefix="/api")
@api.route("/tasks", methods=["GET"])
def list_tasks():
tasks = Task.query.order_by(Task.id).all()
return jsonify([{"id": t.id, "title": t.title, "done": t.done} for t in tasks])
@api.route("/tasks", methods=["POST"])
def create_task():
data = request.get_json(silent=True) or {}
title = (data.get("title") or "").strip()
if not title:
return jsonify(error="title is required"), 400
t = Task(title=title)
db.session.add(t)
db.session.commit()
return jsonify(id=t.id, title=t.title, done=t.done), 201Validation with pydantic
from pydantic import BaseModel, ValidationError, Field
class TaskIn(BaseModel):
title: str = Field(min_length=1, max_length=100)
done: bool = False
@api.route("/tasks", methods=["POST"])
def create_task():
try:
body = TaskIn.model_validate(request.get_json())
except ValidationError as e:
return jsonify(errors=e.errors()), 422
...Error handler
@api.errorhandler(404)
def not_found(e):
return jsonify(error="Not found"), 404