-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathmain.py
More file actions
51 lines (40 loc) · 1.02 KB
/
main.py
File metadata and controls
51 lines (40 loc) · 1.02 KB
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
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
books = [
{"id": 1, "title": "Python Basics", "author": "Real P.", "pages": 635},
{
"id": 2,
"title": "Breaking the Rules",
"author": "Stephen G.",
"pages": 99,
},
]
class Book(BaseModel):
title: str
author: str
pages: int
@app.get("/books")
def get_books(limit: int | None = None):
"""Get all books, optionally limited by count."""
if limit:
return {"books": books[:limit]}
return {"books": books}
@app.get("/books/{book_id}")
def get_book(book_id: int):
"""Get a specific book by ID."""
for book in books:
if book["id"] == book_id:
return book
return {"error": "Book not found"}
@app.post("/books")
def create_book(book: Book):
"""Create a new book entry."""
new_book = {
"id": len(books) + 1,
"title": book.title,
"author": book.author,
"pages": book.pages,
}
books.append(new_book)
return new_book