אתר API עם FastAPIA web API with FastAPI
נתיבים, Pydantic, תיעוד אוטומטי ו-CRUD.
Routes, Pydantic, automatic docs and CRUD.
מודל pydanticA pydantic model
תזכורת: מה ביקשוReminder: the task
כתבו מודל Review עם book: str (לפחות תו אחד), stars: int בין 1 ל-5 (Field(ge=1, le=5)), ו-text: str = "". צרו ביקורת תקינה והדפיסו את model_dump().
Write a Review model with book: str (at least one character), stars: int from 1 to 5 (Field(ge=1, le=5)), and text: str = "". Create a valid review and print model_dump().
הפתרון המלא והפלט שלוFull solution and its output
from pydantic import BaseModel, Field
class Review(BaseModel):
book: str = Field(min_length=1)
stars: int = Field(ge=1, le=5)
text: str = ""
print(Review(book="Dune", stars=5).model_dump()){'book': 'Dune', 'stars': 5, 'text': ''}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לוגיקה בלי שרתLogic without a server
תזכורת: מה ביקשוReminder: the task
כתבו את הלוגיקה של נתיב חיפוש כפונקציה רגילה search(books, q=None, min_pages=0) שמחזירה ספרים שהכותרת או הסופר שלהם מכילים q (בלי רגישות לאותיות; q ריק = כולם) ושיש להם לפחות min_pages עמודים, ממוינים לפי כותרת. כך קל לבדוק אותה, ובשרת מחברים אותה לנתיב.
Write the logic of a search route as a plain function search(books, q=None, min_pages=0) returning books whose title or author contains q (case-insensitive; empty q = all) with at least min_pages pages, sorted by title. That makes it easy to test, and the server just connects it to a route.
הפתרון המלא והפלט שלוFull solution and its output
def search(books, q=None, min_pages=0):
out = []
for b in books:
if q and q.lower() not in (b["title"] + " " + b["author"]).lower():
continue
if b["pages"] < min_pages:
continue
out.append(b)
return sorted(out, key=lambda b: b["title"])
BOOKS = [{"title": "Matilda", "author": "Roald Dahl", "pages": 240}, {"title": "Dune", "author": "Frank Herbert", "pages": 412}, {"title": "The BFG", "author": "Roald Dahl", "pages": 208}]
print([b["title"] for b in search(BOOKS, q="DAHL")])
print([b["title"] for b in search(BOOKS, min_pages=230)])['Matilda', 'The BFG'] ['Dune', 'Matilda']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
קודי תשובהResponse codes
תזכורת: מה ביקשוReminder: the task
בלי FastAPI: כתבו handle(method, path, store) שמדמה שרת קטן לרשימת מטלות ומחזירה (status, body). GET /todos → 200 ורשימה. POST /todos/<text> → 201 ומילון {id, text} חדש. DELETE /todos/<id> → 204 ו-None, או 404 ו-{"detail": "not found"}. כל השאר → 405 ו-{"detail": "not allowed"}.
Without FastAPI: write handle(method, path, store) simulating a tiny to-do server, returning (status, body). GET /todos → 200 and the list. POST /todos/<text> → 201 and a new dict {id, text}. DELETE /todos/<id> → 204 and None, or 404 and {"detail": "not found"}. Anything else → 405 and {"detail": "not allowed"}.
הפתרון המלא והפלט שלוFull solution and its output
def handle(method, path, store):
parts = path.strip("/").split("/")
if parts[0] != "todos":
return 405, {"detail": "not allowed"}
if method == "GET" and len(parts) == 1:
return 200, store
if method == "POST" and len(parts) == 2:
item = {"id": max((t["id"] for t in store), default=0) + 1, "text": parts[1]}
store.append(item)
return 201, item
if method == "DELETE" and len(parts) == 2 and parts[1].isdigit():
for t in store:
if t["id"] == int(parts[1]):
store.remove(t)
return 204, None
return 404, {"detail": "not found"}
return 405, {"detail": "not allowed"}
s = []
print(handle("POST", "/todos/read", s), handle("POST", "/todos/run", s))
print(handle("DELETE", "/todos/1", s), handle("DELETE", "/todos/1", s))
print(handle("GET", "/todos", s), handle("PUT", "/todos/2", s))(201, {'id': 1, 'text': 'read'}) (201, {'id': 2, 'text': 'run'})
(204, None) (404, {'detail': 'not found'})
(200, [{'id': 2, 'text': 'run'}]) (405, {'detail': 'not allowed'})יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עדכון חלקיA partial update
תזכורת: מה ביקשוReminder: the task
כתבו מודל BookPatch שבו כל השדות אופציונליים (title: str | None = None, pages: int | None = Field(default=None, gt=0)), ו-apply_patch(book, patch) שמחזירה מילון חדש עם השדות שנשלחו בלבד מעודכנים (patch.model_dump(exclude_unset=True)).
Write a BookPatch model where every field is optional (title: str | None = None, pages: int | None = Field(default=None, gt=0)), and apply_patch(book, patch) returning a new dict with only the sent fields updated (patch.model_dump(exclude_unset=True)).
הפתרון המלא והפלט שלוFull solution and its output
from pydantic import BaseModel, Field
class BookPatch(BaseModel):
title: str | None = None
pages: int | None = Field(default=None, gt=0)
def apply_patch(book, patch):
return {**book, **patch.model_dump(exclude_unset=True)}
book = {"id": 1, "title": "Dune", "pages": 412}
print(apply_patch(book, BookPatch(pages=604)))
print(book){'id': 1, 'title': 'Dune', 'pages': 604}
{'id': 1, 'title': 'Dune', 'pages': 412}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 29: API מלאShelf, step 29: a full API
תזכורת: מה ביקשוReminder: the task
כתבו מחלקת שירות ShelfService שתשב מאחורי ה-API (בלי FastAPI, כדי שתרוץ גם כאן): add(data) מקבלת dict, בודקת אותו עם המודל BookIn (title לא ריק, author, pages > 0) ומחזירה ספר עם id; get(id) זורקת KeyError אם אין; list(author=None); delete(id) מחזירה True/False. בשרת האמיתי כל נתיב פשוט קורא למתודה המתאימה.
Write a ShelfService class to sit behind the API (without FastAPI, so it runs here too): add(data) takes a dict, validates it with the BookIn model (non-empty title, author, pages > 0) and returns a book with an id; get(id) raises KeyError if missing; list(author=None); delete(id) returns True/False. In the real server each route just calls the matching method.
הפתרון המלא והפלט שלוFull solution and its output
from pydantic import BaseModel, Field
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
class ShelfService:
def __init__(self):
self.books = {}
def add(self, data):
book = BookIn(**data)
new_id = max(self.books, default=0) + 1
self.books[new_id] = {"id": new_id, **book.model_dump()}
return self.books[new_id]
def get(self, book_id):
return self.books[book_id]
def list(self, author=None):
return [b for b in self.books.values() if not author or author.lower() in b["author"].lower()]
def delete(self, book_id):
return self.books.pop(book_id, None) is not None
shelf = ShelfService()
shelf.add({"title": "Dune", "author": "Frank Herbert", "pages": 412})
shelf.add({"title": "Matilda", "author": "Roald Dahl", "pages": 240})
print([b["title"] for b in shelf.list(author="dahl")], shelf.delete(1), shelf.delete(1))['Matilda'] True False
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
נתב משלכםYour own router
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Router עם דקורטור route(method, pattern) ומתודה dispatch(method, path). pattern יכול לכלול {name} (למשל /books/{id}), ו-dispatch מוצאת את הנתיב המתאים, שולפת את הפרמטרים ומעבירה אותם בשם לפונקציה. מחזירה (200, result), או (404, None) אם אין נתיב.
Write a Router class with a route(method, pattern) decorator and a dispatch(method, path) method. pattern may include {name} (e.g. /books/{id}), and dispatch finds the matching route, extracts the parameters and passes them by name to the function. Returns (200, result), or (404, None) if no route matches.
הפתרון המלא והפלט שלוFull solution and its output
class Router:
def __init__(self):
self.routes = []
def route(self, method, pattern):
def deco(fn):
self.routes.append((method, pattern.strip("/").split("/"), fn))
return fn
return deco
def dispatch(self, method, path):
parts = path.strip("/").split("/")
for m, pat, fn in self.routes:
if m != method or len(pat) != len(parts):
continue
params = {}
for p, actual in zip(pat, parts):
if p.startswith("{") and p.endswith("}"):
params[p[1:-1]] = actual
elif p != actual:
break
else:
return 200, fn(**params)
return 404, None
app = Router()
@app.route("GET", "/books/{book_id}")
def get_book(book_id):
return {"id": int(book_id)}
@app.route("GET", "/authors/{name}/books/{n}")
def nth(name, n):
return f"{name} #{n}"
print(app.dispatch("GET", "/books/7"), app.dispatch("GET", "/authors/dahl/books/2"), app.dispatch("POST", "/books/7"))(200, {'id': 7}) (200, 'dahl #2') (404, None)יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
הגבלת קצבRate limiting
תזכורת: מה ביקשוReminder: the task
כתבו RateLimiter(limit, window) עם allow(client, now) שמחזירה True אם ללקוח נשארו בקשות בחלון הזמן האחרון של window שניות (חלון נע), אחרת False (בשרת: 429). בקשות שנדחו לא נספרות.
Write RateLimiter(limit, window) with allow(client, now) returning True if the client still has requests within the last window seconds (a sliding window), else False (in a server: 429). Rejected requests aren't counted.
הפתרון המלא והפלט שלוFull solution and its output
class RateLimiter:
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.hits = {}
def allow(self, client, now):
recent = [t for t in self.hits.get(client, []) if now - t < self.window]
if len(recent) >= self.limit:
self.hits[client] = recent
return False
recent.append(now)
self.hits[client] = recent
return True
rl = RateLimiter(limit=3, window=10)
print([rl.allow("noa", t) for t in (0, 1, 2, 3, 9, 10, 11, 12)])
print(rl.allow("avi", 3))[True, True, True, False, False, True, True, True] True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.