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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Declaring dependencies as parameters lets FastAPI supply and clean up resources like DB sessions per request.
  2. 2A 201 response should point clients to the new resource via a Location header built from named routes.
  3. 3Separate request and response schemas keep input validation and output shape independent from the ORM model.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a REST article resource in FastAPI — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code