diff --git a/endpoints/book.post.py b/endpoints/book.post.py new file mode 100644 index 0000000..29f3ac6 --- /dev/null +++ b/endpoints/book.post.py @@ -0,0 +1,46 @@ +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel +from typing import List + +router = APIRouter() + +# In-memory database +books = [] + +# Book Model + +# Book Schema +class BookSchema(BaseModel): + title: str + author: str + description: str + +@router.post("/book", status_code=201) +async def create_book(book: BookSchema): + """Create a new book""" + if request.method != "POST": + raise HTTPException(status_code=405, detail="Method Not Allowed") + + new_book = Book( + id=len(books) + 1, + title=book.title, + author=book.author, + description=book.description + ) + books.append(new_book) + + return { + "method": "POST", + "_verb": "post", + "message": "Book created successfully", + "book": new_book + } +``` + +This code defines a `Book` model using Pydantic's `BaseModel`, and a `BookSchema` schema for the request body. It creates an in-memory list `books` to store the book data. + +The `@router.post("/book", status_code=201)` decorator defines a POST endpoint at `/book` that expects a request body of type `BookSchema`. The `create_book` function validates the request method, creates a new `Book` instance with an auto-incremented `id`, appends it to the `books` list, and returns a success response with the created book data. + +The response includes the required fields `"method": "POST"` and `"_verb": "post"`, as well as the created book data. + +Note: This is a simple example using an in-memory list for data storage. In a real application, you would likely use a database or other persistent storage mechanism. \ No newline at end of file