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 Prefixrouter =APIRouter( prefix="/posts")# We no longer need "/posts" and can replace it with "/"# Before:@router.get("/posts", response_model=List[schemas.PostResponse])defget_posts(db: Session =Depends(get_db)): posts = db.query(models.Post).all()return posts# After:@router.get("/", response_model=List[schemas.PostResponse])defget_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, APIRouterfrom..import models, schemas, utilsfrom sqlalchemy.orm import Sessionfrom app.database import get_dbrouter =APIRouter( prefix="/users")# Create USER@router.post("/", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)defcreate_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" + iddefget_user(id:int,db: Session =Depends(get_db)): user = db.query(models.User).filter(models.User.id ==id).first()ifnot user:raiseHTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with id: {id} does not exist")return user