From 096b8579d7cf5daecee7114078066f1fcb8a4108 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 18:39:36 +0100 Subject: [PATCH] Add POST endpoint for books --- endpoints/books.post.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 endpoints/books.post.py diff --git a/endpoints/books.post.py b/endpoints/books.post.py new file mode 100644 index 0000000..b49728b --- /dev/null +++ b/endpoints/books.post.py @@ -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 \ No newline at end of file