אתר API עם FastAPIA web API with FastAPI
נתיבים, Pydantic, תיעוד אוטומטי ו-CRUD.
Routes, Pydantic, automatic docs and CRUD.
01שרת ראשוןYour first server
במפגש 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:
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
def home():
return {"message": "Welcome to Shelf", "books": 3}
client = TestClient(app)
r = client.get("/")
print(r.status_code, r.json())200 {'message': 'Welcome to Shelf', 'books': 3}שרת API הוא כמו מוקד טלפוני: יושב ומחכה לשיחות. כל מספר שלוחה (נתיב) מגיע לפקיד אחר (פונקציה).
An API server is like a call centre: it sits waiting for calls. Each extension number (route) reaches a different clerk (function).
שוכחים return, והשרת עונה null.
Forgetting return, so the server answers null.
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
def home():
{"message": "Welcome"}
r = TestClient(app).get("/")
assert r.json() is not None, f"status {r.status_code} but the body is {r.text}: the function forgot return"Traceback (most recent call last):
File "/Users/you/python-course/hello_api.py", line 10, in <module>
assert r.json() is not None, f"status {r.status_code} but the body is {r.text}: the function forgot return"
^^^^^^^^^^^^^^^^^^^^
AssertionError: status 200 but the body is null: the function forgot returnAssertionError: status 200 but the body is null: the function forgot return: פונקציה בלי return מחזירה None, ו-FastAPI שולח null. כותבים return {...}.AssertionError: status 200 but the body is null: the function forgot return: a function without return gives None, and FastAPI sends null. Write return {...}.02נתיבים ופרמטריםRoutes and parameters
נתיב יכול לכלול חלק משתנה: /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):
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Shelf API")
BOOKS = {1: {"id": 1, "title": "Dune", "author": "Frank Herbert", "pages": 412}}
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
@app.get("/books")
def list_books(author: str | None = None):
books = list(BOOKS.values())
if author:
books = [b for b in books if author.lower() in b["author"].lower()]
return books
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail="book not found")
return BOOKS[book_id]
@app.post("/books", status_code=201)
def add_book(book: BookIn):
new_id = max(BOOKS, default=0) + 1
BOOKS[new_id] = {"id": new_id, **book.model_dump()}
return BOOKS[new_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if BOOKS.pop(book_id, None) is None:
raise HTTPException(status_code=404, detail="book not found")from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Shelf API")
BOOKS = {1: {"id": 1, "title": "Dune", "author": "Frank Herbert", "pages": 412}}
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
@app.get("/books")
def list_books(author: str | None = None):
books = list(BOOKS.values())
if author:
books = [b for b in books if author.lower() in b["author"].lower()]
return books
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail="book not found")
return BOOKS[book_id]
@app.post("/books", status_code=201)
def add_book(book: BookIn):
new_id = max(BOOKS, default=0) + 1
BOOKS[new_id] = {"id": new_id, **book.model_dump()}
return BOOKS[new_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if BOOKS.pop(book_id, None) is None:
raise HTTPException(status_code=404, detail="book not found")
from fastapi.testclient import TestClient
client = TestClient(app)
print(client.get("/books/1").json())
print(client.get("/books", params={"author": "herbert"}).json())
r = client.get("/books/abc")
print(r.status_code, r.json()["detail"][0]["msg"]){'id': 1, 'title': 'Dune', 'author': 'Frank Herbert', 'pages': 412}
[{'id': 1, 'title': 'Dune', 'author': 'Frank Herbert', 'pages': 412}]
422 Input should be a valid integer, unable to parse string as an integerפרמטר בנתיב הוא כמו מספר דירה בכתובת: אותו בניין, דלת אחרת. פרמטר שאילתה הוא כמו הערה למשלוח: "להשאיר ליד הדלת".
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".
שם הפרמטר בנתיב שונה מהשם בפונקציה.
The parameter name in the path differs from the function's.
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/books/{book_id}")
def get_book(id: int):
return {"id": id}
r = TestClient(app).get("/books/7")
assert r.status_code == 200, f"{r.status_code}: {r.json()['detail'][0]['msg']} (FastAPI looked for a query parameter named id)"Traceback (most recent call last):
File "/Users/you/python-course/main.py", line 10, in <module>
assert r.status_code == 200, f"{r.status_code}: {r.json()['detail'][0]['msg']} (FastAPI looked for a query parameter named id)"
^^^^^^^^^^^^^^^^^^^^
AssertionError: 422: Field required (FastAPI looked for a query parameter named id)AssertionError: 422: Field required ...: FastAPI לא חיבר את {book_id} ל-id, וחשב ש-id הוא פרמטר שאילתה חסר. השמות חייבים להיות זהים.AssertionError: 422: Field required ...: FastAPI didn't link {book_id} to id, and thought id was a missing query parameter. The names must match.שרת בוחר פונקציה לפי הכתובת. הנה הרעיון במילון.
A server picks a function by the address. Here's the idea with a dict.
def home():
return "Welcome"
def about():
return "About us"
ROUTES = {"/": home, "/about": about}
for path in ["/", "/about"]:
print(path, ROUTES[path]())/ Welcome /about About us
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03קלט בטוח עם pydanticSafe input with pydantic
כשמישהו שולח ספר חדש ב-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.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Shelf API")
BOOKS = {1: {"id": 1, "title": "Dune", "author": "Frank Herbert", "pages": 412}}
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
@app.get("/books")
def list_books(author: str | None = None):
books = list(BOOKS.values())
if author:
books = [b for b in books if author.lower() in b["author"].lower()]
return books
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail="book not found")
return BOOKS[book_id]
@app.post("/books", status_code=201)
def add_book(book: BookIn):
new_id = max(BOOKS, default=0) + 1
BOOKS[new_id] = {"id": new_id, **book.model_dump()}
return BOOKS[new_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if BOOKS.pop(book_id, None) is None:
raise HTTPException(status_code=404, detail="book not found")
from fastapi.testclient import TestClient
client = TestClient(app)
r = client.post("/books", json={"title": "Emma", "author": "Jane Austen", "pages": 474})
print(r.status_code, r.json())
r = client.post("/books", json={"title": "", "author": "X", "pages": -5})
print(r.status_code)
for problem in r.json()["detail"]:
print(" ", problem["loc"][-1], "->", problem["msg"])201 {'id': 2, 'title': 'Emma', 'author': 'Jane Austen', 'pages': 474}
422
title -> String should have at least 1 character
pages -> Input should be greater than 0מודל 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.
שולחים את הגוף כ-params במקום json.
Sending the body as params instead of json.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Shelf API")
BOOKS = {1: {"id": 1, "title": "Dune", "author": "Frank Herbert", "pages": 412}}
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
@app.get("/books")
def list_books(author: str | None = None):
books = list(BOOKS.values())
if author:
books = [b for b in books if author.lower() in b["author"].lower()]
return books
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail="book not found")
return BOOKS[book_id]
@app.post("/books", status_code=201)
def add_book(book: BookIn):
new_id = max(BOOKS, default=0) + 1
BOOKS[new_id] = {"id": new_id, **book.model_dump()}
return BOOKS[new_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if BOOKS.pop(book_id, None) is None:
raise HTTPException(status_code=404, detail="book not found")
from fastapi.testclient import TestClient
client = TestClient(app)
r = client.post("/books", params={"title": "Emma", "author": "Jane Austen", "pages": 474})
assert r.status_code == 201, f"{r.status_code}: {r.json()['detail'][0]['msg']}"Traceback (most recent call last):
File "/Users/you/python-course/validate.py", line 46, in <module>
assert r.status_code == 201, f"{r.status_code}: {r.json()['detail'][0]['msg']}"
^^^^^^^^^^^^^^^^^^^^
AssertionError: 422: Field requiredAssertionError: 422: Field required: המודל מצפה לגוף JSON. שולחים json={...}.AssertionError: 422: Field required: the model expects a JSON body. Send json={...}.04שגיאות וקודי סטטוסErrors and status codes
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.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Shelf API")
BOOKS = {1: {"id": 1, "title": "Dune", "author": "Frank Herbert", "pages": 412}}
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
@app.get("/books")
def list_books(author: str | None = None):
books = list(BOOKS.values())
if author:
books = [b for b in books if author.lower() in b["author"].lower()]
return books
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail="book not found")
return BOOKS[book_id]
@app.post("/books", status_code=201)
def add_book(book: BookIn):
new_id = max(BOOKS, default=0) + 1
BOOKS[new_id] = {"id": new_id, **book.model_dump()}
return BOOKS[new_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if BOOKS.pop(book_id, None) is None:
raise HTTPException(status_code=404, detail="book not found")
from fastapi.testclient import TestClient
client = TestClient(app)
print(client.delete("/books/1").status_code)
print(client.delete("/books/1").status_code, client.delete("/books/1").json())
print(client.get("/books/1").json())
print(client.get("/books").json())204
404 {'detail': 'book not found'}
{'detail': 'book not found'}
[]קוד סטטוס הוא כמו פתק שהשליח משאיר: "נמסר" (200), "הושאר חבילה חדשה" (201), "הכתובת לא קיימת" (404).
A status code is like the courier's note: "delivered" (200), "new parcel left" (201), "address doesn't exist" (404).
מחזירים dict של שגיאה עם קוד 200.
Returning an error dict with a 200 code.
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/books/{book_id}")
def get_book(book_id: int):
return {"error": "not found"}
r = TestClient(app).get("/books/99")
assert r.status_code == 404, f"status {r.status_code}: clients will think it worked"Traceback (most recent call last):
File "/Users/you/python-course/errors.py", line 10, in <module>
assert r.status_code == 404, f"status {r.status_code}: clients will think it worked"
^^^^^^^^^^^^^^^^^^^^
AssertionError: status 200: clients will think it workedAssertionError: status 200: clients will think it worked: תוכנה שקוראת ל-API בודקת את הקוד, לא את הטקסט. זורקים HTTPException(status_code=404).AssertionError: status 200: clients will think it worked: software calling the API checks the code, not the text. Raise HTTPException(status_code=404).05להריץ באמת: uvicorn ו-/docsRunning for real: uvicorn and /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).
uvicorn main:app --reloadINFO: Will watch for changes in these directories: ['/Users/you/python-course'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [4242] using WatchFiles INFO: Started server process [4244] INFO: Waiting for application startup. INFO: Application startup complete. INFO: 127.0.0.1:52811 - "GET /books HTTP/1.1" 200 OK
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Shelf API")
BOOKS = {1: {"id": 1, "title": "Dune", "author": "Frank Herbert", "pages": 412}}
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
@app.get("/books")
def list_books(author: str | None = None):
books = list(BOOKS.values())
if author:
books = [b for b in books if author.lower() in b["author"].lower()]
return books
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail="book not found")
return BOOKS[book_id]
@app.post("/books", status_code=201)
def add_book(book: BookIn):
new_id = max(BOOKS, default=0) + 1
BOOKS[new_id] = {"id": new_id, **book.model_dump()}
return BOOKS[new_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if BOOKS.pop(book_id, None) is None:
raise HTTPException(status_code=404, detail="book not found")
from fastapi.testclient import TestClient
client = TestClient(app)
schema = client.get("/openapi.json").json()
print(schema["info"]["title"])
for path, methods in schema["paths"].items():
print(path, sorted(m.upper() for m in methods))Shelf API
/books ['GET', 'POST']
/books/{book_id} ['DELETE', 'GET']/docs הוא כמו תפריט במסעדה שהמטבח מדפיס לבד מהמתכונים: תמיד מעודכן, ואפשר להזמין ממנו ישירות.
/docs is like a menu the kitchen prints itself from the recipes: always up to date, and you can order straight from it.
מריצים uvicorn עם שם קובץ שגוי.
Running uvicorn with the wrong file name.
python3 -c "import importlib; importlib.import_module('mian')"Traceback (most recent call last):
File "<string>", line 1, in <module>
import importlib; importlib.import_module('mian')
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
File "/usr/local/lib/python3.13/importlib/__init__.py", line 88, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1404, in _gcd_import
File "<frozen importlib._bootstrap>", line 1369, in _find_and_load
File "<frozen importlib._bootstrap>", line 1333, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'mian'ModuleNotFoundError: No module named 'mian': uvicorn מחפש את הקובץ mian.py. הצורה היא קובץ:משתנה, כאן main:app, ומריצים מאותה תיקייה.ModuleNotFoundError: No module named 'mian': uvicorn looks for mian.py. The form is file:variable, here main:app, run from that same folder.06לבדוק API עם pytestTesting an API with pytest
כל מה שעשינו עם 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:
from fastapi.testclient import TestClient
from main import app, BOOKS
client = TestClient(app)
def test_get_existing():
assert client.get("/books/1").json()["title"] == "Dune"
def test_missing_is_404():
assert client.get("/books/999").status_code == 404
def test_add_and_find():
r = client.post("/books", json={"title": "Emma", "author": "Jane Austen", "pages": 474})
assert r.status_code == 201
assert client.get("/books", params={"author": "austen"}).json()[0]["title"] == "Emma"
def test_rejects_bad_pages():
assert client.post("/books", json={"title": "X", "author": "Y", "pages": 0}).status_code == 422python3 -m pytest -q.... [100%] 4 passed in 0.01s
TestClient הוא כמו סימולטור טיסה: אותם כפתורים ואותן תגובות, בלי להמריא באמת.
TestClient is like a flight simulator: the same buttons and responses, without really taking off.
בדיקות שתלויות בסדר, כי הנתונים משותפים.
Tests that depend on order because data is shared.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Shelf API")
BOOKS = {1: {"id": 1, "title": "Dune", "author": "Frank Herbert", "pages": 412}}
class BookIn(BaseModel):
title: str = Field(min_length=1)
author: str
pages: int = Field(gt=0)
@app.get("/books")
def list_books(author: str | None = None):
books = list(BOOKS.values())
if author:
books = [b for b in books if author.lower() in b["author"].lower()]
return books
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail="book not found")
return BOOKS[book_id]
@app.post("/books", status_code=201)
def add_book(book: BookIn):
new_id = max(BOOKS, default=0) + 1
BOOKS[new_id] = {"id": new_id, **book.model_dump()}
return BOOKS[new_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if BOOKS.pop(book_id, None) is None:
raise HTTPException(status_code=404, detail="book not found")
from fastapi.testclient import TestClient
client = TestClient(app)
client.delete("/books/1")
r = client.get("/books/1")
assert r.status_code == 200, "an earlier test deleted book 1: reset BOOKS in a fixture before each test"Traceback (most recent call last):
File "/Users/you/python-course/test_main.py", line 47, in <module>
assert r.status_code == 200, "an earlier test deleted book 1: reset BOOKS in a fixture before each test"
^^^^^^^^^^^^^^^^^^^^
AssertionError: an earlier test deleted book 1: reset BOOKS in a fixture before each testAssertionError: an earlier test deleted book 1: ...: מילון גלובלי זוכר בין בדיקות. fixture שמחזיר את BOOKS למצב התחלתי לפני כל בדיקה פותר את זה.AssertionError: an earlier test deleted book 1: ...: a global dict remembers between tests. A fixture restoring BOOKS before each test fixes it.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.