41 lines
1.3 KiB
Python
41 lines
1.3 KiB
Python
from fastapi import APIRouter, HTTPException
|
|
|
|
books = [] # In-memory storage
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("/books")
|
|
async def save_book(
|
|
title: str,
|
|
author: str,
|
|
description: str = None
|
|
):
|
|
"""Save a new book to the database"""
|
|
if request.method != "POST":
|
|
raise HTTPException(status_code=405, detail="Method Not Allowed")
|
|
|
|
book = {
|
|
"title": title,
|
|
"author": author,
|
|
"description": description
|
|
}
|
|
books.append(book)
|
|
|
|
return {
|
|
"message": "Book saved successfully",
|
|
"book": book,
|
|
"method": "POST",
|
|
"_verb": "post"
|
|
}
|
|
```
|
|
|
|
This endpoint follows the provided rules and examples:
|
|
|
|
1. It uses the `@router.post` decorator for the `/books` path.
|
|
2. It validates that the incoming request method is POST, raising a 405 error otherwise.
|
|
3. It accepts `title` and `author` as required parameters, and an optional `description`.
|
|
4. It creates a new book dictionary with the provided data.
|
|
5. It appends the new book to the `books` list (in-memory storage).
|
|
6. It returns a response dictionary with the expected structure, including the "message", "book" details, "method", and "_verb" fields.
|
|
|
|
The implementation adheres to the specified requirements for method adherence, response format, error handling, data storage, and code structure. |