36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
import models
|
|
from database import get_db
|
|
from typing import List
|
|
from pydantic import BaseModel
|
|
router = APIRouter()
|
|
class ClientCreate(BaseModel):
|
|
name: str
|
|
class ClientOut(ClientCreate):
|
|
id: int
|
|
class Config:
|
|
orm_mode = True
|
|
@router.post("/", response_model=ClientOut, status_code=status.HTTP_201_CREATED)
|
|
def create_client(client: ClientCreate, db: Session = Depends(get_db)):
|
|
db_client = models.Client(name=client.name)
|
|
db.add(db_client)
|
|
try:
|
|
db.commit()
|
|
db.refresh(db_client)
|
|
except Exception as e:
|
|
db.rollback()
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
return db_client
|
|
@router.get("/", response_model=List[ClientOut])
|
|
def list_clients(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
clients = db.query(models.Client).offset(skip).limit(limit).all()
|
|
return clients
|
|
@router.get("/{client_id}", response_model=ClientOut)
|
|
def get_client(client_id: int, db: Session = Depends(get_db)):
|
|
client = db.query(models.Client).filter(models.Client.id == client_id).first()
|
|
if not client:
|
|
raise HTTPException(status_code=404, detail="Client not found")
|
|
return client
|
|
|