WIP: initial fastapi endpoint implementation
Client endpoint - GET & POST implemented
This commit is contained in:
@@ -1,7 +0,0 @@
|
||||
"""
|
||||
API Home
|
||||
"""
|
||||
from fastapi import APIRouter
|
||||
|
||||
|
||||
api_router = APIRouter()
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
The Client table
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from sqlmodel import Session, select
|
||||
from app.api.deps import SessionDep, exists
|
||||
from app.schemas.models import Client
|
||||
from app.schemas.schemas import ClientCreate
|
||||
from typing import Sequence
|
||||
|
||||
router = APIRouter(prefix="/clients", tags=["clients"])
|
||||
|
||||
|
||||
@router.get("/", response_model=Client)
|
||||
def fetch_clients(client: Client, session: SessionDep) -> Sequence[Client]:
|
||||
"""Fetch client list
|
||||
"""
|
||||
clients = session.exec(select(Client)).all()
|
||||
return clients
|
||||
|
||||
|
||||
@router.post("/", response_model=ClientCreate)
|
||||
def create_client(client_data: ClientCreate, session: SessionDep) -> Client:
|
||||
existing = exists(session, Client, tin_number=client_data.tin_number)
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Client with this tin number already exists")
|
||||
client = Client.model_validate(client_data)
|
||||
session.add(client)
|
||||
session.commit()
|
||||
session.refresh(client)
|
||||
return client
|
||||
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
"""
|
||||
from fastapi import Depends
|
||||
from sqlmodel import Session, SQLModel, select
|
||||
from app.core.db import get_session
|
||||
from app.schemas.models import Client
|
||||
from typing import Type, Optional, Annotated
|
||||
|
||||
|
||||
SessionDep = Annotated[Session, Depends(get_session)]
|
||||
|
||||
|
||||
def exists(session: Session, model: Type[SQLModel], **filters) -> Optional[bool]:
|
||||
"""
|
||||
Checks if a request exists in the given model using any filters.
|
||||
|
||||
Example:
|
||||
exists(session, Client, phone="0781232465", tax_number="TIN123")
|
||||
"""
|
||||
if not filters:
|
||||
raise ValueError("At least one filter must be provided")
|
||||
|
||||
stmt = select(model)
|
||||
for field, value in filters.items():
|
||||
if not hasattr(model, field):
|
||||
raise ValueError(f"Invalid filter field: {field}")
|
||||
stmt = stmt.where(getattr(model, field) == value)
|
||||
|
||||
result = session.exec(stmt).first()
|
||||
return result is not None
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
API Home
|
||||
"""
|
||||
from fastapi import APIRouter
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
#if settings.environment == "local":
|
||||
# api_router.include_router()
|
||||
Reference in New Issue
Block a user