59 lines
1.8 KiB
Python
59 lines
1.8 KiB
Python
"""This module contains endpoints for operations related to users."""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from backend.database.engine import get_db
|
|
import backend.schemas.users as userschema
|
|
import backend.crud.users as usercrud
|
|
from backend.exceptions import NotFoundException
|
|
|
|
|
|
router = APIRouter(
|
|
prefix="/users",
|
|
tags=["users"]
|
|
)
|
|
|
|
tag_metadata = {
|
|
"name": "users",
|
|
"description": "Operations related to users."
|
|
}
|
|
|
|
|
|
@router.post("/users/", response_model=userschema.User)
|
|
def create_user(user: userschema.UserCreate, db: Session = Depends(get_db)):
|
|
existing_user = usercrud.read_user_by_email(db, email=user.email)
|
|
if existing_user:
|
|
raise HTTPException(400, "A user with this email address is already registered.")
|
|
return usercrud.create_user(db=db, user=user)
|
|
|
|
|
|
@router.get("/users/{id}", response_model=userschema.User)
|
|
def read_user(id: int, db: Session = Depends(get_db)):
|
|
try:
|
|
return usercrud.read_user(db=db, id=id)
|
|
except NotFoundException as e:
|
|
raise HTTPException(404, str(e))
|
|
|
|
|
|
@router.get("/users/", response_model=list[userschema.User])
|
|
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
users = usercrud.read_users(db=db, skip=skip, limit=limit)
|
|
return users
|
|
|
|
|
|
@router.patch("/users/{id}", response_model=userschema.User)
|
|
def update_user(id: int, user: userschema.UserUpdate, db: Session = Depends(get_db)):
|
|
try:
|
|
return usercrud.update_user(db=db, user=user, id=id)
|
|
except NotFoundException as e:
|
|
raise HTTPException(404, str(e))
|
|
|
|
|
|
@router.delete("/users/{id}", response_model=userschema.User)
|
|
def delete_user(id: int, db: Session = Depends(get_db)):
|
|
try:
|
|
return usercrud.delete_user(db=db, id=id)
|
|
except NotFoundException as e:
|
|
raise HTTPException(404, str(e))
|