diff --git a/endpoints/book.post.py b/endpoints/book.post.py index 29f3ac6..640b23e 100644 --- a/endpoints/book.post.py +++ b/endpoints/book.post.py @@ -1,46 +1,36 @@ from fastapi import APIRouter, HTTPException -from pydantic import BaseModel -from typing import List +from pydantic import BaseModel, Field +from typing import Optional router = APIRouter() -# In-memory database +# In-memory storage books = [] -# Book Model + class Config: + schema_extra = { + "example": { + "title": "Book Title", + "author": "Author Name", + "description": "Book description", + "rating": 4 + } + } -# Book Schema -class BookSchema(BaseModel): - title: str - author: str - description: str - -@router.post("/book", status_code=201) -async def create_book(book: BookSchema): +@router.post("/book", response_model=BookModel) +async def create_book(book: BookModel): """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) + book.id = len(books) + 1 + books.append(book) return { "method": "POST", "_verb": "post", - "message": "Book created successfully", - "book": new_book + **book.dict() } ``` -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 +This code defines a `BookModel` using Pydantic, which includes validation rules for each field. The `create_book` endpoint accepts a `BookModel` instance in the request body, assigns a new `id`, appends it to the `books` list, and returns the created book object along with the HTTP method metadata. \ No newline at end of file