|
| 1 | +from typing import List |
| 2 | + |
| 3 | +from core import get_mongodb |
| 4 | +from fastapi import APIRouter, Body, Depends, HTTPException, Response, status |
| 5 | +from fastapi.encoders import jsonable_encoder |
| 6 | +from loguru import logger |
| 7 | +from models import Book, BookUpdate |
| 8 | + |
| 9 | +# https://pymongo.readthedocs.io/en/stable/tutorial.html |
| 10 | +from pymongo.database import Database |
| 11 | + |
| 12 | +router = APIRouter( |
| 13 | + prefix="/books", |
| 14 | + tags=["books"], |
| 15 | + dependencies=[Depends(get_mongodb)], |
| 16 | + responses={404: {"description": "API Not found"}}, |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +@router.post( |
| 21 | + "/", |
| 22 | + response_description="Create a new book", |
| 23 | + status_code=status.HTTP_201_CREATED, |
| 24 | + response_model=Book, |
| 25 | +) |
| 26 | +def create_book(book: Book = Body(...), *, db: Database = Depends(get_mongodb)): |
| 27 | + """ |
| 28 | + curl -X POST "http://localhost:8000/books/" -H "Content-Type: application/json" -d '''{ "_id": "066de609-b04a-4b30-b46c-32537c7f1f6e", |
| 29 | + "title": "Don Quixote", |
| 30 | + "author": "Miguel de Cervantes", |
| 31 | + "synopsis": "..." |
| 32 | + } |
| 33 | + ''' |
| 34 | + """ |
| 35 | + book = jsonable_encoder(book) |
| 36 | + new_book = db["books"].insert_one(book) |
| 37 | + created_book = db["books"].find_one({"_id": new_book.inserted_id}) |
| 38 | + logger.info(f"created_book = {created_book}") |
| 39 | + return created_book |
| 40 | + |
| 41 | + |
| 42 | +@router.get("/", response_description="List all books", response_model=List[Book]) |
| 43 | +def list_books(*, db: Database = Depends(get_mongodb)): |
| 44 | + books = list(db["books"].find(limit=100)) |
| 45 | + logger.info(f"books.size = {len(books)}") |
| 46 | + return books |
| 47 | + |
| 48 | + |
| 49 | +@router.get("/{id}", response_description="Get a single book by id", response_model=Book) |
| 50 | +def find_book(id: str, *, db: Database = Depends(get_mongodb)): |
| 51 | + if (book := db["books"].find_one({"_id": id})) is not None: |
| 52 | + return book |
| 53 | + |
| 54 | + raise HTTPException( |
| 55 | + status_code=status.HTTP_404_NOT_FOUND, detail=f"Book with ID {id} not found" |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +@router.put("/{id}", response_description="Update a book", response_model=Book) |
| 60 | +def update_book(id: str, *, db: Database = Depends(get_mongodb), book: BookUpdate = Body(...)): |
| 61 | + """ |
| 62 | + curl -X PUT "http://localhost:8000/books/066de609-b04a-4b30-b46c-32537c7f1f6e" -H "Content-Type: application/json" -d '''{ |
| 63 | + "title": "Don Quixote", |
| 64 | + "author": "Miguel de Cervantes", |
| 65 | + "synopsis": "Don Quixote is a Spanish novel by Miguel de Cervantes..." |
| 66 | + } |
| 67 | + ''' |
| 68 | + """ |
| 69 | + book = {k: v for k, v in book.dict().items() if v is not None} |
| 70 | + |
| 71 | + if len(book) >= 1: |
| 72 | + update_result = db["books"].update_one({"_id": id}, {"$set": book}) |
| 73 | + |
| 74 | + if update_result.modified_count == 0: |
| 75 | + raise HTTPException( |
| 76 | + status_code=status.HTTP_404_NOT_FOUND, detail=f"Book with ID {id} not found" |
| 77 | + ) |
| 78 | + |
| 79 | + # Walrus Operator (since Python 3.8) |
| 80 | + if (existing_book := db["books"].find_one({"_id": id})) is not None: |
| 81 | + return existing_book |
| 82 | + |
| 83 | + raise HTTPException( |
| 84 | + status_code=status.HTTP_404_NOT_FOUND, detail=f"Book with ID {id} not found" |
| 85 | + ) |
| 86 | + |
| 87 | + |
| 88 | +@router.delete("/{id}", response_description="Delete a book") |
| 89 | +def delete_book(id: str, *, db: Database = Depends(get_mongodb), response: Response): |
| 90 | + delete_result = db["books"].delete_one({"_id": id}) |
| 91 | + |
| 92 | + if delete_result.deleted_count == 1: |
| 93 | + response.status_code = status.HTTP_204_NO_CONTENT |
| 94 | + return response |
| 95 | + |
| 96 | + raise HTTPException( |
| 97 | + status_code=status.HTTP_404_NOT_FOUND, detail=f"Book with ID {id} not found" |
| 98 | + ) |
0 commit comments