python 40 lines · 7 steps

Building a REST articles API with Flask Blueprints

A Flask Blueprint groups four CRUD endpoints for articles, each handling querying, validation, and serialization.

Explained by highlit
1from flask import Blueprint, jsonify, request, abort
2 
3from .models import Article, db
4from .schemas import article_schema, articles_schema
5 
6bp = Blueprint("articles", __name__, url_prefix="/api/articles")
7 
8 
9@bp.get("/")
10def list_articles():
11 query = Article.query.filter_by(published=True)
12 if tag := request.args.get("tag"):
13 query = query.filter(Article.tags.any(name=tag))
14 articles = query.order_by(Article.created_at.desc()).all()
15 return jsonify(articles_schema.dump(articles))
16 
17 
18@bp.get("/<int:article_id>")
19def get_article(article_id):
20 article = Article.query.get_or_404(article_id)
21 return jsonify(article_schema.dump(article))
22 
23 
24@bp.post("/")
25def create_article():
26 errors = article_schema.validate(request.json or {})
27 if errors:
28 abort(422, description=errors)
29 article = Article(**article_schema.load(request.json))
30 db.session.add(article)
31 db.session.commit()
32 return jsonify(article_schema.dump(article)), 201
33 
34 
35@bp.delete("/<int:article_id>")
36def delete_article(article_id):
37 article = Article.query.get_or_404(article_id)
38 db.session.delete(article)
39 db.session.commit()
40 return "", 204
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Blueprints let you group related routes under a shared URL prefix so the API stays modular.
  2. 2Schemas centralize validation and serialization, keeping route handlers focused on data flow.
  3. 3Returning the right status code — 201 for creation, 204 for deletion — makes a REST API predictable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a REST articles API with Flask Blueprints — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code