Skip to content

Commit c8954b3

Browse files
committed
adding validator to disallow duplicate books
1 parent 4128cbb commit c8954b3

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

models.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,35 @@ class Config:
1919
}
2020
}
2121

22+
class BookCreate(BaseModel):
23+
id: str = Field(default_factory=uuid.uuid4, alias="_id")
24+
title: str = Field(...)
25+
author: str = Field(...)
26+
synopsis: str = Field(...)
27+
28+
class Config:
29+
allow_population_by_field_name = True
30+
schema_extra = {
31+
"example": {
32+
"title": "Don Quixote",
33+
"author": "Miguel de Cervantes",
34+
"synopsis": "..."
35+
}
36+
}
37+
class BookCreate(BaseModel):
38+
title: str = Field(...)
39+
author: str = Field(...)
40+
synopsis: str = Field(...)
41+
42+
class Config:
43+
allow_population_by_field_name = True
44+
schema_extra = {
45+
"example": {
46+
"title": "Don Quixote",
47+
"author": "Miguel de Cervantes",
48+
"synopsis": "..."
49+
}
50+
}
2251

2352
class BookUpdate(BaseModel):
2453
title: Optional[str]

routes.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
11
from fastapi import APIRouter, Body, Request, Response, HTTPException, status
22
from fastapi.encoders import jsonable_encoder
33
from typing import List
4-
5-
from models import Book, BookUpdate
4+
import uuid
5+
from models import Book, BookUpdate, BookCreate
66

77
router = APIRouter()
88

99
@router.post("/", response_description="Create a new book", status_code=status.HTTP_201_CREATED, response_model=Book)
10-
def create_book(request: Request, book: Book = Body(...)):
10+
def create_book(request: Request, book: BookCreate = Body(...)):
1111
book = jsonable_encoder(book)
12+
book["_id"] = str(uuid.uuid4())
13+
14+
# verify if book title already exists
15+
if request.app.database["books"].find_one({"title": book["title"]}):
16+
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Book with title {book['title']} already exists")
17+
18+
1219
new_book = request.app.database["books"].insert_one(book)
1320
created_book = request.app.database["books"].find_one(
1421
{"_id": new_book.inserted_id}

0 commit comments

Comments
 (0)