fastapiu-iqm25e/endpoints/books.post.py
2025-03-25 08:40:29 +01:00

34 lines
1.1 KiB
Python

from fastapi import APIRouter, HTTPException
import uuid
books = [] # In-memory storage
router = APIRouter()
@router.post("/books")
async def create_book(
title: str,
author: str,
description: str = None
):
"""Create a new book"""
if request.method != "POST":
raise HTTPException(status_code=405, detail="Method Not Allowed")
book_id = str(uuid.uuid4())
books.append({
"id": book_id,
"title": title,
"author": author,
"description": description
})
return {
"message": "Book created successfully",
"book_id": book_id,
"method": "POST",
"_verb": "post"
}
```
This code defines a POST endpoint at `/books` that creates a new book entry in an in-memory list called `books`. It takes the `title` and `author` as required parameters, and an optional `description`. It generates a unique `book_id` using `uuid.uuid4()` and appends a new dictionary to the `books` list with the provided data. The response includes a success message, the generated `book_id`, and the expected `method` and `_verb` fields.