From 44b0c20d265a668fa8038829768a61cb9cd4f4d6 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Mon, 24 Mar 2025 23:55:53 +0100 Subject: [PATCH] Update code in endpoints/books.post.py --- endpoints/books.post.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 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..fe6dddb --- /dev/null +++ b/endpoints/books.post.py @@ -0,0 +1,38 @@ +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel +from typing import List + +router = APIRouter() + +# Model +class Book(BaseModel): + id: int + title: str + author: str + pages: int + +# Database (in-memory storage) +books: List[Book] = [] + +@router.post("/books", status_code=201) +async def create_book(book: Book): + """Create a new book""" + if request.method != "POST": + raise HTTPException(status_code=405, detail="Method Not Allowed") + + book.id = len(books) + 1 + books.append(book) + + return { + "message": "Book created successfully", + "book": book, + "method": "POST", + "_verb": "post" + } +``` + +This code defines a `Book` model using Pydantic's `BaseModel`, and an in-memory `books` list to store the book data. The `@router.post("/books")` endpoint accepts a `Book` object in the request body, assigns it a new `id`, appends it to the `books` list, and returns a success response with the created book object and metadata about the HTTP method used. + +The code also includes a check for the HTTP method, raising a `405 Method Not Allowed` exception if the request method is not `POST`. The response includes the `"method": "POST"` and `"_verb": "post"` fields as required. + +Note that this is a basic example, and in a real-world application, you would likely use a database instead of an in-memory list, and implement additional features such as data validation, error handling, and authentication/authorization. \ No newline at end of file