נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
29
חלקPart 5: בונים דבריםBuilding things כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

אתר API עם FastAPIA web API with FastAPI

נתיבים, Pydantic, תיעוד אוטומטי ו-CRUD.

Routes, Pydantic, automatic docs and CRUD.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. מה עושה @app.get("/books")?What does @app.get("/books") do?

2. מה יחזיר השרת ל-/books/abc כש-book_id: int?What does the server return for /books/abc when book_id: int?

3. איזה קוד מתאים ליצירת ספר חדש?Which code fits creating a new book?

תרגיליםExercises

תרגילExercise 1

מודל pydanticA pydantic model

כתבו מודל 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().

איך הפלט אמור להיראות?What should the output look like?
{'book': 'Dune', 'stars': 5, 'text': ''}
main.py
רמזHint 1: from pydantic import BaseModel, Fieldfrom pydantic import BaseModel, Field
רמזHint 2: stars: int = Field(ge=1, le=5)stars: int = Field(ge=1, le=5)
לפתרוןSolution
תרגילExercise 2

לוגיקה בלי שרתLogic without a server

כתבו את הלוגיקה של נתיב חיפוש כפונקציה רגילה 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.

איך הפלט אמור להיראות?What should the output look like?
['Matilda', 'The BFG']
['Dune', 'Matilda']
main.py
רמזHint 1: if q and q.lower() not in (b["title"] + " " + b["author"]).lower(): continueif q and q.lower() not in (b["title"] + " " + b["author"]).lower(): continue
רמזHint 2: sorted(..., key=lambda b: b["title"])sorted(..., key=lambda b: b["title"])
לפתרוןSolution
תרגילExercise 3

קודי תשובהResponse codes

בלי 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"}.

איך הפלט אמור להיראות?What should the output look like?
(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'})
main.py
רמזHint 1: parts = path.strip("/").split("/")parts = path.strip("/").split("/")
רמזHint 2: id חדש: max((t["id"] for t in store), default=0) + 1A new id: max((t["id"] for t in store), default=0) + 1
לפתרוןSolution
תרגילExercise 4

עדכון חלקיA partial update

כתבו מודל 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)).

איך הפלט אמור להיראות?What should the output look like?
{'id': 1, 'title': 'Dune', 'pages': 604}
{'id': 1, 'title': 'Dune', 'pages': 412}
main.py
רמזHint 1: {**book, **patch.model_dump(exclude_unset=True)}{**book, **patch.model_dump(exclude_unset=True)}
רמזHint 2: exclude_unset משאיר בחוץ שדות שלא נשלחו בכלל.exclude_unset leaves out fields that weren't sent at all.
לפתרוןSolution
תרגילExercise 5

מדף, צעד 29: API מלאShelf, step 29: a full API

פרויקט מלווהCompanion project

כתבו מחלקת שירות 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.

איך הפלט אמור להיראות?What should the output look like?
['Matilda'] True False
service.py
רמזHint 1: book = BookIn(**data) זורקת ValidationError על קלט שגוי.book = BookIn(**data) raises ValidationError on bad input.
רמזHint 2: self.books[new_id] = {"id": new_id, **book.model_dump()}self.books[new_id] = {"id": new_id, **book.model_dump()}
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

נתב משלכםYour own router

כתבו מחלקה 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.

איך הפלט אמור להיראות?What should the output look like?
(200, {'id': 7}) (200, 'dahl #2') (404, None)
main.py
רמזHint 1: השוו קטע אחרי קטע: p.startswith("{") הוא פרמטר.Compare segment by segment: p.startswith("{") is a parameter.
רמזHint 2: דקורטור מחזיר פונקציה: def deco(fn): self.routes.append(...); return fn.A decorator returns a function: def deco(fn): self.routes.append(...); return fn.
לפתרוןSolution
אתגרChallenge 2

הגבלת קצבRate limiting

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
[True, True, True, False, False, True, True, True]
True
main.py
רמזHint 1: שמרו לכל לקוח רשימת זמנים.Keep a list of times per client.
רמזHint 2: מנקים זמנים ישנים: [t for t in times if now - t < window].Drop old times: [t for t in times if now - t < window].
לפתרוןSolution

נבנה על ידיBuilt by Ariel Yohimovich