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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Blueprints let you group related routes under a shared URL prefix so the API stays modular.
- 2Schemas centralize validation and serialization, keeping route handlers focused on data flow.
- 3Returning the right status code — 201 for creation, 204 for deletion — makes a REST API predictable.
Related explainers
python
import csv from collections import defaultdict from dataclasses import dataclass, field from decimal import Decimal, InvalidOperation
Aggregating CSV sales by category in Python
dataclasses
csv-parsing
defaultdict
Intermediate
8 steps
ruby
class ConfigFlattener def initialize(config) @config = config end
Flattening nested config into dotted keys
recursion
hashes
tree-traversal
Intermediate
8 steps
java
@RestController @RequestMapping("/api/users") public class UserController {
Bean Validation in a Spring REST controller
validation
rest-api
exception-handling
Intermediate
9 steps
javascript
const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); };
Async error handling in Express routes
async-await
error-handling
middleware
Intermediate
7 steps
python
from django.core.cache import cache from rest_framework.throttling import SimpleRateThrottle
A login rate throttle in Django REST Framework
rate-limiting
caching
throttling
Intermediate
8 steps
python
import stripe from fastapi import APIRouter, Request, Header, HTTPException from app.config import settings
Handling Stripe webhooks in FastAPI
webhooks
signature-verification
event-routing
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/building-a-rest-articles-api-with-flask-blueprints-explained-python-ac10/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.