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 fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 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.