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 datetime from dataclasses import dataclass
Parsing fixed-width records in Python
parsing
generators
dataclasses
Intermediate
8 steps
python
from itertools import product from dataclasses import dataclass from decimal import Decimal
Generating product variants with itertools.product
cartesian-product
dataclass
decimal
Intermediate
7 steps
python
from typing import Callable, Dict, Type class PluginRegistry:
A decorator-based plugin registry in Python
decorators
registry pattern
factory
Intermediate
9 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
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.