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

חזרה למפגשBack
PythonPython

אתר API עם FastAPIA web API with FastAPI

מפגש 29: נתיבים, Pydantic, תיעוד אוטומטי ו-CRUD.Session 29: Routes, Pydantic, automatic docs and CRUD.

מה נעשה היוםToday's plan

  • שרתServer
  • נתיביםRoutes
  • pydanticpydantic
  • שגיאותErrors
  • הרצהRunning
  • בדיקותTests
נושאTopic 1

שרתServer

שרת ראשוןYour first server

  • app = FastAPI()app = FastAPI()
  • @app.get("/") מעל פונקציה@app.get("/") above a function
  • מחזירים dict → מקבלים JSONReturn a dict → get JSON

אנלוגיהAnalogy

שרת API הוא כמו מוקד טלפוני: יושב ומחכה לשיחות. כל מספר שלוחה (נתיב) מגיע לפקיד אחר (פונקציה).An API server is like a call centre: it sits waiting for calls. Each extension number (route) reaches a different clerk (function).
נושאTopic 2

נתיביםRoutes

נתיבים ופרמטריםRoutes and parameters

  • פרמטר בנתיב: /books/{book_id}Path parameter: /books/{book_id}
  • פרמטר שאילתה: ?author=dahlQuery parameter: ?author=dahl
  • הטיפוס בחתימה = בדיקה + המרהThe type in the signature = check + convert

אנלוגיה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".
נושאTopic 3

pydanticpydantic

קלט בטוח עם pydanticSafe input with pydantic

  • class BookIn(BaseModel) מגדיר מבנהclass BookIn(BaseModel) defines a shape
  • Field(gt=0, min_length=1) מוסיף כלליםField(gt=0, min_length=1) adds rules
  • קלט שגוי → 422 עם הסבר, בלי קוד שלנוBad input → 422 with an explanation, no code of ours

אנלוגיה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.
נושאTopic 4

שגיאותErrors

שגיאות וקודי סטטוסErrors and status codes

  • raise HTTPException(404, ...)raise HTTPException(404, ...)
  • status_code=201 ליצירה, 204 למחיקהstatus_code=201 for create, 204 for delete
  • CRUD = POST, GET, PUT, DELETECRUD = POST, GET, PUT, DELETE

אנלוגיהAnalogy

קוד סטטוס הוא כמו פתק שהשליח משאיר: "נמסר" (200), "הושאר חבילה חדשה" (201), "הכתובת לא קיימת" (404).A status code is like the courier's note: "delivered" (200), "new parcel left" (201), "address doesn't exist" (404).
נושאTopic 5

הרצהRunning

להריץ באמת: uvicorn ו-/docsRunning for real: uvicorn and /docs

  • pip install fastapi "uvicorn[standard]"pip install fastapi "uvicorn[standard]"
  • uvicorn main:app --reloaduvicorn main:app --reload
  • http://127.0.0.1:8000/docs = תיעוד חיhttp://127.0.0.1:8000/docs = live docs

אנלוגיה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.
נושאTopic 6

בדיקותTests

לבדוק API עם pytestTesting an API with pytest

  • TestClient(app) בתוך בדיקותTestClient(app) inside tests
  • בודקים קוד + גוףCheck code + body
  • fixture שמאפס את הנתוניםA fixture that resets the data

אנלוגיהAnalogy

TestClient הוא כמו סימולטור טיסה: אותם כפתורים ואותן תגובות, בלי להמריא באמת.TestClient is like a flight simulator: the same buttons and responses, without really taking off.

app = FastAPI()app = FastAPI()

@app.get("/") מעל פונקציה@app.get("/") above a function

מחזירים dict → מקבלים JSONReturn a dict → get JSON

פרמטר בנתיב: /books/{book_id}Path parameter: /books/{book_id}

פרמטר שאילתה: ?author=dahlQuery parameter: ?author=dahl

הטיפוס בחתימה = בדיקה + המרהThe type in the signature = check + convert

class BookIn(BaseModel) מגדיר מבנהclass BookIn(BaseModel) defines a shape

Field(gt=0, min_length=1) מוסיף כלליםField(gt=0, min_length=1) adds rules

קלט שגוי → 422 עם הסבר, בלי קוד שלנוBad input → 422 with an explanation, no code of ours

raise HTTPException(404, ...)raise HTTPException(404, ...)

status_code=201 ליצירה, 204 למחיקהstatus_code=201 for create, 204 for delete

CRUD = POST, GET, PUT, DELETECRUD = POST, GET, PUT, DELETE

pip install fastapi "uvicorn[standard]"pip install fastapi "uvicorn[standard]"

uvicorn main:app --reloaduvicorn main:app --reload

http://127.0.0.1:8000/docs = תיעוד חיhttp://127.0.0.1:8000/docs = live docs

TestClient(app) בתוך בדיקותTestClient(app) inside tests

בודקים קוד + גוףCheck code + body

fixture שמאפס את הנתוניםA fixture that resets the data

מה למדנוWhat we learned

  • app = FastAPI()app = FastAPI()
  • פרמטר בנתיב: /books/{book_id}Path parameter: /books/{book_id}
  • class BookIn(BaseModel) מגדיר מבנהclass BookIn(BaseModel) defines a shape
  • raise HTTPException(404, ...)raise HTTPException(404, ...)
  • pip install fastapi "uvicorn[standard]"pip install fastapi "uvicorn[standard]"
  • TestClient(app) בתוך בדיקותTestClient(app) inside tests

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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