36 lines
1.1 KiB
Python
36 lines
1.1 KiB
Python
from fastapi import APIRouter, HTTPException
|
|
from pydantic import BaseModel, Field
|
|
from typing import Optional
|
|
|
|
router = APIRouter()
|
|
|
|
# In-memory storage
|
|
books = []
|
|
|
|
class Config:
|
|
schema_extra = {
|
|
"example": {
|
|
"title": "Book Title",
|
|
"author": "Author Name",
|
|
"description": "Book description",
|
|
"rating": 4
|
|
}
|
|
}
|
|
|
|
@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")
|
|
|
|
book.id = len(books) + 1
|
|
books.append(book)
|
|
|
|
return {
|
|
"method": "POST",
|
|
"_verb": "post",
|
|
**book.dict()
|
|
}
|
|
```
|
|
|
|
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. |