Router Prefix

  • Complex APIs can have very complex and long routes

  • Router Prefixes allow us to have that stored

  • We can additionally replace the route with "/"

# Stored Prefix
router = APIRouter(
    prefix="/posts"
)

# We no longer need "/posts" and can replace it with "/"

# Before:
@router.get("/posts", response_model=List[schemas.PostResponse])
def get_posts(db: Session = Depends(get_db)):


    posts = db.query(models.Post).all()

    return posts
    
# After:
@router.get("/", response_model=List[schemas.PostResponse])
def get_posts(db: Session = Depends(get_db)):


    posts = db.query(models.Post).all()

    return posts

How it looks with the full code for the users.py file

from fastapi import Depends, FastAPI, Response, status, HTTPException, APIRouter
from .. import models, schemas, utils
from sqlalchemy.orm import Session
from app.database import get_db

router = APIRouter(
    prefix="/users"
)

# Create USER
@router.post("/", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):

    # Hash the Password - user.password
    hashed_password = utils.hash(user.password)
    user.password = hashed_password

    new_user = models.User(**user.dict())

    db.add(new_user)
    db.commit()
    db.refresh(new_user)

    return new_user


# Get USER by ID
@router.get("/{id}", response_model=schemas.UserOut) # This will append it to "/users" + id
def get_user(id: int, db: Session = Depends(get_db)):

    user = db.query(models.User).filter(models.User.id == id).first()

    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with id: {id} does not exist")

    return user

Last updated