31 lines
1.1 KiB
Python
31 lines
1.1 KiB
Python
from fastapi import APIRouter, HTTPException, status, Depends
|
|
from sqlalchemy.orm import Session
|
|
from typing import List
|
|
from app.schemas import ContactPerson, ContactPersonCreate
|
|
from app.models import ContactPerson as ContactPersonModel
|
|
from app.dependencies import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/", response_model=List[ContactPerson])
|
|
async def get_contacts(db: Session = Depends(get_db)):
|
|
return db.query(ContactPersonModel).all()
|
|
|
|
@router.post("/", response_model=ContactPerson, status_code=status.HTTP_201_CREATED)
|
|
async def create_contact(contact: ContactPersonCreate, db: Session = Depends(get_db)):
|
|
if db.query(ContactPersonModel).filter(ContactPersonModel.email == contact.email).first():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="This contact already exists."
|
|
)
|
|
|
|
db_contact = ContactPersonModel(
|
|
firstname=contact.firstname,
|
|
lastname=contact.lastname,
|
|
phone_number=contact.phone_number,
|
|
email=contact.email
|
|
)
|
|
db.add(db_contact)
|
|
db.commit()
|
|
db.refresh(db_contact)
|
|
return db_contact |