From c75c8ad71b5d542749f4b08a15f42ddae96156e4 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 00:20:14 +0100 Subject: [PATCH] Update code in endpoints/booknies.post.py --- endpoints/booknies.post.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 endpoints/booknies.post.py diff --git a/endpoints/booknies.post.py b/endpoints/booknies.post.py new file mode 100644 index 0000000..1ec5cc2 --- /dev/null +++ b/endpoints/booknies.post.py @@ -0,0 +1,36 @@ +from fastapi import APIRouter, HTTPException +import uuid + +books = [] # In-memory storage + +router = APIRouter() + +# Book Model +class Book: + def __init__(self, title, author, description): + self.id = str(uuid.uuid4()) + self.title = title + self.author = author + self.description = description + +# Book Schema + +@router.post("/booknies") +async def create_book(book: BookSchema): + """Create a new book""" + if any(b.title == book.title for b in books): + raise HTTPException(status_code=400, detail="Book already exists") + + new_book = Book(book.title, book.author, book.description) + books.append(new_book.__dict__) + + return { + "message": "Book created successfully", + "book_id": new_book.id, + "title": new_book.title, + "author": new_book.author, + "description": new_book.description + } +``` + +This code defines a POST endpoint `/booknies` that creates a new book in the in-memory `books` list. It includes a `Book` model class to represent a book, and a `BookSchema` Pydantic model for data validation. The endpoint checks if a book with the same title already exists, and if not, creates a new `Book` instance and appends it to the `books` list. The response includes the details of the newly created book. \ No newline at end of file