
- Set up FastAPI application with SQLite database - Implement User and Item models with relationships - Add CRUD operations for users and items - Configure Alembic for database migrations - Include API documentation at /docs and /redoc - Add health check endpoint at /health - Enable CORS for all origins - Structure code with proper separation of concerns
67 lines
1.8 KiB
Python
67 lines
1.8 KiB
Python
from typing import Any, List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from app import crud, schemas
|
|
from app.db.session import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("/", response_model=schemas.User)
|
|
def create_user(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
user_in: schemas.UserCreate,
|
|
) -> Any:
|
|
user = crud.user.get_by_email(db, email=user_in.email)
|
|
if user:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="The user with this email already exists in the system.",
|
|
)
|
|
user = crud.user.create(db, obj_in=user_in)
|
|
return user
|
|
|
|
@router.get("/", response_model=List[schemas.User])
|
|
def read_users(
|
|
db: Session = Depends(get_db),
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
) -> Any:
|
|
users = crud.user.get_multi(db, skip=skip, limit=limit)
|
|
return users
|
|
|
|
@router.get("/{user_id}", response_model=schemas.User)
|
|
def read_user(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
user_id: int,
|
|
) -> Any:
|
|
user = crud.user.get(db, id=user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
return user
|
|
|
|
@router.put("/{user_id}", response_model=schemas.User)
|
|
def update_user(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
user_id: int,
|
|
user_in: schemas.UserUpdate,
|
|
) -> Any:
|
|
user = crud.user.get(db, id=user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
user = crud.user.update(db, db_obj=user, obj_in=user_in)
|
|
return user
|
|
|
|
@router.delete("/{user_id}")
|
|
def delete_user(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
user_id: int,
|
|
) -> Any:
|
|
user = crud.user.get(db, id=user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
user = crud.user.remove(db, id=user_id)
|
|
return {"message": "User deleted successfully"} |