36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
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. |