Skip to content

Commit 362551c

Browse files
committed
Replace code in main file
1 parent 863a59d commit 362551c

File tree

2 files changed

+48
-56
lines changed

2 files changed

+48
-56
lines changed

fastapi/books_api.py

Lines changed: 0 additions & 53 deletions
This file was deleted.

fastapi/main.py

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,53 @@
1+
from typing import Optional
2+
3+
from pydantic import BaseModel
4+
15
from fastapi import FastAPI
26

37
app = FastAPI()
48

9+
books = [
10+
{"id": 1, "title": "Python Basics", "author": "Real P.", "pages": 635},
11+
{
12+
"id": 2,
13+
"title": "Breaking the Rules",
14+
"author": "Stephen G.",
15+
"pages": 99,
16+
},
17+
]
18+
19+
20+
class Book(BaseModel):
21+
title: str
22+
author: str
23+
pages: int
24+
25+
26+
@app.get("/books")
27+
def get_books(limit: Optional[int] = None):
28+
"""Get all books, optionally limited by count."""
29+
if limit:
30+
return {"books": books[:limit]}
31+
return {"books": books}
32+
33+
34+
@app.get("/books/{book_id}")
35+
def get_book(book_id: int):
36+
"""Get a specific book by ID."""
37+
for book in books:
38+
if book["id"] == book_id:
39+
return book
40+
return {"error": "Book not found"}
41+
542

6-
@app.get("/")
7-
def home():
8-
return {"message": "Hello, FastAPI!"}
43+
@app.post("/books")
44+
def create_book(book: Book):
45+
"""Create a new book entry."""
46+
new_book = {
47+
"id": len(books) + 1,
48+
"title": book.title,
49+
"author": book.author,
50+
"pages": book.pages,
51+
}
52+
books.append(new_book)
53+
return new_book

0 commit comments

Comments
 (0)