|
| 1 | +from fastapi import APIRouter, Body, Request, Response, HTTPException, status |
| 2 | +from fastapi.encoders import jsonable_encoder |
| 3 | + |
| 4 | +from models import Book, BookUpdate |
| 5 | + |
| 6 | +router = APIRouter() |
| 7 | + |
| 8 | +@router.post("/", response_description="Create a new book", status_code=status.HTTP_201_CREATED) |
| 9 | +def create_book(request: Request, book: Book = Body(...)): |
| 10 | + book = jsonable_encoder(book) |
| 11 | + new_book = request.app.database["books"].insert_one(book) |
| 12 | + created_book = request.app.database["books"].find_one( |
| 13 | + {"_id": new_book.inserted_id} |
| 14 | + ) |
| 15 | + |
| 16 | + return created_book |
| 17 | + |
| 18 | + |
| 19 | +@router.get("/", response_description="List all books") |
| 20 | +def list_books(request: Request): |
| 21 | + books = list(request.app.database["books"].find(limit=100)) |
| 22 | + return books |
| 23 | + |
| 24 | +@router.get("/{id}", response_description="Get a single book by id") |
| 25 | +def find_book(id: str, request: Request): |
| 26 | + if (book := request.app.database["books"].find_one({"_id": id})) is not None: |
| 27 | + return book |
| 28 | + |
| 29 | + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Book with ID {id} not found") |
| 30 | + |
| 31 | + |
| 32 | +@router.put("/{id}", response_description="Update a book") |
| 33 | +def update_book(id: str, request: Request, book: BookUpdate = Body(...)): |
| 34 | + book = {k: v for k, v in book.dict().items() if v is not None} |
| 35 | + |
| 36 | + if len(book) >= 1: |
| 37 | + update_result = request.app.database["books"].update_one( |
| 38 | + {"_id": id}, {"$set": book} |
| 39 | + ) |
| 40 | + |
| 41 | + if update_result.modified_count == 1: |
| 42 | + if ( |
| 43 | + updated_book := request.app.database["books"].find_one({"_id": id}) |
| 44 | + ) is not None: |
| 45 | + return updated_book |
| 46 | + |
| 47 | + if ( |
| 48 | + existing_book := request.app.database["books"].find_one({"_id": id}) |
| 49 | + ) is not None: |
| 50 | + return existing_book |
| 51 | + |
| 52 | + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Book with ID {id} not found") |
| 53 | + |
| 54 | + |
| 55 | +@router.delete("/{id}", response_description="Delete a book") |
| 56 | +def delete_book(id: str, request: Request, response: Response): |
| 57 | + delete_result = request.app.database["books"].delete_one({"_id": id}) |
| 58 | + |
| 59 | + if delete_result.deleted_count == 1: |
| 60 | + response.status_code = status.HTTP_204_NO_CONTENT |
| 61 | + return response |
| 62 | + |
| 63 | + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Book with ID {id} not found") |
0 commit comments