Skip to content

Commit 9cb4f37

Browse files
committed
Updated main.py
1 parent 9103a13 commit 9cb4f37

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

‎main.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from fastapi import FastAPI, HTTPException
2+
from fastapi.middleware.cors import CORSMiddleware
3+
from pydantic import BaseModel
4+
from typing import Optional
5+
6+
app = FastAPI()
7+
8+
# Allow browser requests from file:// and localhost (needed for the Python Bootcamp simulator)
9+
app.add_middleware(
10+
CORSMiddleware,
11+
allow_origins=["*"],
12+
allow_methods=["*"],
13+
allow_headers=["*"],
14+
)
15+
16+
class Book(BaseModel):
17+
title: str
18+
price: float
19+
category: str
20+
21+
books_db = [
22+
{"id": 1, "title": "Clean Code", "price": 29.99, "category": "tech"},
23+
{"id": 2, "title": "Dune", "price": 14.99, "category": "sci-fi"},
24+
{"id": 3, "title": "The Pragmatic Programmer", "price": 34.99, "category": "tech"},
25+
]
26+
27+
@app.get("/")
28+
def root():
29+
return {"message": "Book Store API", "total": len(books_db)}
30+
31+
@app.get("/books")
32+
def get_books(category: Optional[str] = None):
33+
if category:
34+
return [b for b in books_db if b["category"] == category]
35+
return books_db
36+
37+
@app.post("/books", status_code=201)
38+
def create_book(book: Book):
39+
new_book = {"id": len(books_db) + 1, **book.dict()}
40+
books_db.append(new_book)
41+
return new_book
42+
43+
@app.delete("/books/{book_id}")
44+
def delete_book(book_id: int):
45+
book = next((b for b in books_db if b["id"] == book_id), None)
46+
if not book:
47+
raise HTTPException(status_code=404, detail="Book not found")
48+
books_db.remove(book)
49+
return {"deleted": book_id}

0 commit comments

Comments
 (0)