Update code in endpoints/books.post.py
This commit is contained in:
parent
0f5970deb9
commit
44b0c20d26
38
endpoints/books.post.py
Normal file
38
endpoints/books.post.py
Normal file
@ -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.
|
Loading…
x
Reference in New Issue
Block a user