-
Notifications
You must be signed in to change notification settings - Fork 67
/
main.py
71 lines (50 loc) · 1.47 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import json
import os
from typing import Literal, Optional
from uuid import uuid4
from fastapi import FastAPI, HTTPException
import random
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from mangum import Mangum
class Book(BaseModel):
name: str
genre: Literal["fiction", "non-fiction"]
price: float
book_id: Optional[str] = uuid4().hex
BOOKS_FILE = "books.json"
BOOKS = []
if os.path.exists(BOOKS_FILE):
with open(BOOKS_FILE, "r") as f:
BOOKS = json.load(f)
app = FastAPI()
handler = Mangum(app)
@app.get("/")
async def root():
return {"message": "Welcome to my bookstore app!"}
@app.get("/random-book")
async def random_book():
return random.choice(BOOKS)
@app.get("/list-books")
async def list_books():
return {"books": BOOKS}
@app.get("/book_by_index/{index}")
async def book_by_index(index: int):
if index < len(BOOKS):
return BOOKS[index]
else:
raise HTTPException(404, f"Book index {index} out of range ({len(BOOKS)}).")
@app.post("/add-book")
async def add_book(book: Book):
book.book_id = uuid4().hex
json_book = jsonable_encoder(book)
BOOKS.append(json_book)
with open(BOOKS_FILE, "w") as f:
json.dump(BOOKS, f)
return {"book_id": book.book_id}
@app.get("/get-book")
async def get_book(book_id: str):
for book in BOOKS:
if book.book_id == book_id:
return book
raise HTTPException(404, f"Book ID {book_id} not found in database.")