python
38 lines · 8 steps
Building a REST article resource in FastAPI
A router pairs a create endpoint that returns a Location header with a fetch endpoint, wired to SQLAlchemy through dependency injection.
Explained by
highlit
1from fastapi import APIRouter, Depends, Response, status
2from sqlalchemy.orm import Session
3
4from .database import get_db
5from .schemas import ArticleCreate, ArticleRead
6from . import models
7
8router = APIRouter(prefix="/articles", tags=["articles"])
9
10
11@router.post(
12 "",
13 response_model=ArticleRead,
14 status_code=status.HTTP_201_CREATED,
15)
16def create_article(
17 payload: ArticleCreate,
18 response: Response,
19 db: Session = Depends(get_db),
20) -> models.Article:
21 article = models.Article(
22 title=payload.title,
23 slug=payload.slug,
24 body=payload.body,
25 )
26 db.add(article)
27 db.commit()
28 db.refresh(article)
29
30 response.headers["Location"] = router.url_path_for(
31 "get_article", article_id=article.id
32 )
33 return article
34
35
36@router.get("/{article_id}", response_model=ArticleRead)
37def get_article(article_id: int, db: Session = Depends(get_db)) -> models.Article:
38 return db.query(models.Article).get(article_id)
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Declaring dependencies as parameters lets FastAPI supply and clean up resources like DB sessions per request.
- 2A 201 response should point clients to the new resource via a Location header built from named routes.
- 3Separate request and response schemas keep input validation and output shape independent from the ORM model.
Related explainers
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
python
import time from flask import Flask, g, request
Timing requests with Flask hooks
middleware
request-lifecycle
instrumentation
Intermediate
5 steps
python
from pathlib import Path from PIL import Image, ImageOps
Batch image resizing with Pillow
image-processing
batch-jobs
error-handling
Intermediate
8 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-article-resource-in-fastapi-explained-python-c1ac/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.