Add POST endpoint for books
This commit is contained in:
parent
80c923767b
commit
096b8579d7
21
endpoints/books.post.py
Normal file
21
endpoints/books.post.py
Normal file
@ -0,0 +1,21 @@
|
||||
# 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
|
Loading…
x
Reference in New Issue
Block a user