38 lines
1.5 KiB
Python
38 lines
1.5 KiB
Python
"""User API endpoints."""
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
|
|
from app.api.deps import get_user_service
|
|
from app.models.user import UserCreate, UserRead
|
|
from app.services.user_service import UserAlreadyExistsError, UserNotFoundError, UserService
|
|
|
|
router = APIRouter(prefix="/users", tags=["users"])
|
|
|
|
|
|
@router.get("/", response_model=list[UserRead])
|
|
async def list_users(service: UserService = Depends(get_user_service)) -> list[UserRead]:
|
|
users = await service.list_users()
|
|
return [UserRead.model_validate(user) for user in users]
|
|
|
|
|
|
@router.post("/", response_model=UserRead, status_code=status.HTTP_201_CREATED)
|
|
async def create_user(
|
|
user_in: UserCreate,
|
|
service: UserService = Depends(get_user_service),
|
|
) -> UserRead:
|
|
try:
|
|
user = await service.create_user(user_in)
|
|
except UserAlreadyExistsError as exc: # pragma: no cover - thin API layer
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
|
|
return UserRead.model_validate(user)
|
|
|
|
|
|
@router.get("/{user_id}", response_model=UserRead)
|
|
async def get_user(user_id: int, service: UserService = Depends(get_user_service)) -> UserRead:
|
|
try:
|
|
user = await service.get_user(user_id)
|
|
except UserNotFoundError as exc: # pragma: no cover - thin API layer
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
return UserRead.model_validate(user)
|