נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • app = FastAPI()app = FastAPI()
  • @app.get("/") מעל פונקציה@app.get("/") above a function
  • פרמטר בנתיב: /books/{book_id}Path parameter: /books/{book_id}
  • פרמטר שאילתה: ?author=dahlQuery parameter: ?author=dahl
  • class BookIn(BaseModel) מגדיר מבנהclass BookIn(BaseModel) defines a shape
  • Field(gt=0, min_length=1) מוסיף כלליםField(gt=0, min_length=1) adds rules
  • raise HTTPException(404, ...)raise HTTPException(404, ...)
  • status_code=201 ליצירה, 204 למחיקהstatus_code=201 for create, 204 for delete
  • pip install fastapi "uvicorn[standard]"pip install fastapi "uvicorn[standard]"

מונחיםTerms

  • שרת APIweb API server: תוכנה שמחכה לבקשות HTTP ועונה בנתונים, כמו Open Library, רק שלכם.A program that waits for HTTP requests and answers with data, like Open Library, only yours.
  • FastAPIFastAPI: ספרייה מודרנית לבניית API בפייתון, שמשתמשת ברמזי טיפוס כדי לבדוק קלט וליצור תיעוד אוטומטי.A modern library for building APIs in Python that uses type hints to validate input and generate docs automatically.
  • נתיב (route)route: שילוב של שיטה וכתובת (GET /books) שמחובר לפונקציה שעונה עליו.A method and path (GET /books) linked to the function that answers it.
  • פרמטר בנתיבpath parameter: חלק משתנה בכתובת: /books/{book_id}. FastAPI ממיר אותו לטיפוס שבחתימה.A variable part of the address: /books/{book_id}. FastAPI converts it to the type in the signature.
  • pydanticpydantic: ספרייה שמגדירה מבנה נתונים עם רמזי טיפוס ובודקת שהקלט מתאים, עם הודעות שגיאה מפורטות.A library that defines a data shape with type hints and checks input fits it, with detailed error messages.
  • uvicornuvicorn: השרת שמריץ אפליקציית FastAPI ומקשיב לבקשות. uvicorn main:app --reload.The server that runs a FastAPI app and listens for requests. uvicorn main:app --reload.
  • CRUDCRUD: ארבע הפעולות הבסיסיות על נתונים: Create, Read, Update, Delete. ב-HTTP: POST, GET, PUT/PATCH, DELETE.The four basic data operations: Create, Read, Update, Delete. In HTTP: POST, GET, PUT/PATCH, DELETE.

Cheatsheet

שרתServer
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/")
def home():
נתיביםRoutes
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}}

pydanticpydantic
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}}

שגיאותErrors
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}}

הרצהRunning
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}}

בדיקותTests
from fastapi.testclient import TestClient
from main import app, BOOKS

client = TestClient(app)


def test_get_existing():

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorשוכחים return, והשרת עונה null.Forgetting return, so the server answers null.AssertionError: 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 {...}.
AssertionErrorשם הפרמטר בנתיב שונה מהשם בפונקציה.The parameter name in the path differs from the function's.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.
AssertionErrorשולחים את הגוף כ-params במקום json.Sending the body as params instead of json.AssertionError: 422: Field required: המודל מצפה לגוף JSON. שולחים json={...}.AssertionError: 422: Field required: the model expects a JSON body. Send json={...}.
AssertionErrorמחזירים dict של שגיאה עם קוד 200.Returning an error dict with a 200 code.AssertionError: 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).
AssertionErrorבדיקות שתלויות בסדר, כי הנתונים משותפים.Tests that depend on order because data is shared.AssertionError: 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.

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