21 lines
847 B
Python
21 lines
847 B
Python
# Entity: Book
|
|
|
|
@router.post("/books", status_code=status.HTTP_201_CREATED)
|
|
async def create_book(book: BookCreate, author_filter: str = None, title_filter: str = None, db: Session = Depends(get_db)):
|
|
if author_filter:
|
|
author = db.query(Author).filter(Author.name.ilike(f"%{author_filter}%")).first()
|
|
if not author:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Author not found")
|
|
book.author_id = author.id
|
|
|
|
if title_filter:
|
|
existing_book = db.query(Book).filter(Book.title.ilike(f"%{title_filter}%")).first()
|
|
if existing_book:
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Book with similar title already exists")
|
|
|
|
new_book = Book(**book.dict())
|
|
db.add(new_book)
|
|
db.commit()
|
|
db.refresh(new_book)
|
|
|
|
return new_book |