נתיבים, Pydantic, תיעוד אוטומטי ו-CRUD. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Routes, Pydantic, automatic docs and CRUD. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
שרתServer
נתיביםRoutes
pydanticpydantic
שגיאותErrors
הרצהRunning
בדיקותTests
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
שרתServer
שרת ראשוןYour first server
app = FastAPI()app = FastAPI()
@app.get("/") מעל פונקציה@app.get("/") above a function
מחזירים dict → מקבלים JSONReturn a dict → get JSON
במפגש 22 דיברנו עם API של אחרים. עכשיו נבנה אחד משלנו. ב-FastAPI כותבים פונקציה רגילה ומעליה דקורטור שאומר לאיזו כתובת היא עונה. מה שהיא מחזירה הופך ל-JSON. כדי לנסות בלי שרת אמיתי, TestClient שולח בקשות ישר לאפליקציה:In session 22 we talked to other people's APIs. Now we'll build our own. In FastAPI you write a normal function with a decorator above it saying which address it answers. Whatever it returns becomes JSON. To try it without a real server, TestClient sends requests straight to the app:
אנלוגיהAnalogy
שרת API הוא כמו מוקד טלפוני: יושב ומחכה לשיחות. כל מספר שלוחה (נתיב) מגיע לפקיד אחר (פונקציה).An API server is like a call centre: it sits waiting for calls. Each extension number (route) reaches a different clerk (function).
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
הטיפוס בחתימה = בדיקה + המרהThe type in the signature = check + convert
נתיב יכול לכלול חלק משתנה: /books/{book_id}. כשכותבים בחתימה book_id: int, FastAPI ממיר את "7" למספר, ואם מישהו שולח abc הוא עונה לבד בשגיאה 422. פרמטר שלא מופיע בנתיב הופך לפרמטר שאילתה (?author=...), ו-None כברירת מחדל הופך אותו לאופציונלי. הנה ה-API המלא של המדף (main.py):A route can include a variable part: /books/{book_id}. When the signature says book_id: int, FastAPI converts "7" to a number, and if someone sends abc it answers with a 422 error by itself. A parameter not in the path becomes a query parameter (?author=...), and a None default makes it optional. Here's the full shelf API (main.py):
אנלוגיהAnalogy
פרמטר בנתיב הוא כמו מספר דירה בכתובת: אותו בניין, דלת אחרת. פרמטר שאילתה הוא כמו הערה למשלוח: "להשאיר ליד הדלת".A path parameter is like a flat number in an address: same building, different door. A query parameter is like a delivery note: "leave it by the door".
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 3
pydanticpydantic
קלט בטוח עם pydanticSafe input with pydantic
class BookIn(BaseModel) מגדיר מבנהclass BookIn(BaseModel) defines a shape
קלט שגוי → 422 עם הסבר, בלי קוד שלנוBad input → 422 with an explanation, no code of ours
כשמישהו שולח ספר חדש ב-POST, צריך לוודא שיש כותרת, שהעמודים מספר חיובי, וכן הלאה. pydantic עושה את זה עם מחלקה שנראית כמו dataclass. FastAPI קורא את הגוף, בודק מול המודל, ואם משהו לא תקין, עונה 422 עם רשימה מדויקת של הבעיות, עוד לפני שהפונקציה שלנו רצה.When someone POSTs a new book, you must make sure there's a title, pages is a positive number, and so on. pydantic does it with a class that looks like a dataclass. FastAPI reads the body, checks it against the model, and if something's off answers 422 with an exact list of problems, before our function even runs.
אנלוגיהAnalogy
מודל pydantic הוא כמו שומר בכניסה לאירוע עם רשימה: מי שלא עומד בתנאים לא נכנס, והשומר אומר בדיוק למה.A pydantic model is like a doorman with a guest list: whoever doesn't meet the rules doesn't get in, and the doorman says exactly why.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
status_code=201 ליצירה, 204 למחיקהstatus_code=201 for create, 204 for delete
CRUD = POST, GET, PUT, DELETECRUD = POST, GET, PUT, DELETE
API טוב מחזיר את הקוד הנכון: 201 כשנוצר משהו, 204 כשנמחק ואין מה להחזיר, ו-404 כשמבקשים משהו שלא קיים. HTTPException עוצרת את הפונקציה ושולחת את הקוד וההסבר. ארבע הפעולות על נתונים נקראות CRUD, ולכל אחת שיטת HTTP משלה.A good API returns the right code: 201 when something was created, 204 when deleted and there's nothing to return, and 404 when asking for something that doesn't exist. HTTPException stops the function and sends the code and explanation. The four data operations are called CRUD, each with its own HTTP method.
אנלוגיהAnalogy
קוד סטטוס הוא כמו פתק שהשליח משאיר: "נמסר" (200), "הושאר חבילה חדשה" (201), "הכתובת לא קיימת" (404).A status code is like the courier's note: "delivered" (200), "new parcel left" (201), "address doesn't exist" (404).
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 5
הרצהRunning
להריץ באמת: uvicorn ו-/docsRunning for real: uvicorn and /docs
http://127.0.0.1:8000/docs = תיעוד חיhttp://127.0.0.1:8000/docs = live docs
על המחשב שלכם מתקינים, ומריצים את השרת עם uvicorn: main הוא שם הקובץ ו-app שם המשתנה. --reload מפעיל מחדש בכל שמירה. פותחים בדפדפן http://127.0.0.1:8000/docs, ומקבלים דף תיעוד אינטראקטיבי שנבנה לבד מהקוד ומרמזי הטיפוס: אפשר לנסות כל נתיב בלחיצה (Try it out).On your computer, install, then run the server with uvicorn: main is the file name and app the variable name. --reload restarts on every save. Open http://127.0.0.1:8000/docs in the browser and you get an interactive docs page built automatically from the code and type hints: try any route with a click (Try it out).
אנלוגיהAnalogy
/docs הוא כמו תפריט במסעדה שהמטבח מדפיס לבד מהמתכונים: תמיד מעודכן, ואפשר להזמין ממנו ישירות./docs is like a menu the kitchen prints itself from the recipes: always up to date, and you can order straight from it.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 6
בדיקותTests
לבדוק API עם pytestTesting an API with pytest
TestClient(app) בתוך בדיקותTestClient(app) inside tests
כל מה שעשינו עם TestClient הוא בעצם בדיקה. מכניסים אותו לקובץ test_main.py, ו-pytest מריץ את כל ה-API בלי רשת ובלי שרת. כאן הבדיקות רצות באמת:Everything we did with TestClient is really a test. Put it in test_main.py, and pytest runs the whole API with no network and no server. Here the tests really run:
אנלוגיהAnalogy
TestClient הוא כמו סימולטור טיסה: אותם כפתורים ואותן תגובות, בלי להמריא באמת.TestClient is like a flight simulator: the same buttons and responses, without really taking off.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
app = FastAPI()app = FastAPI()
שרת ראשוןYour first server
@app.get("/") מעל פונקציה@app.get("/") above a function
שרת ראשוןYour first server
מחזירים dict → מקבלים JSONReturn a dict → get JSON