請求與回應模型

使用 FastAPI 將 AI 佈署到生產環境

Matt Eckerle

Software and Data Engineering Leader

API 的請求與回應結構

請求結構
  • 用戶端送到 API 的資料
  • 通常包含:
    • HTTP 方法(GET、POST 等)
    • 標頭(Headers)
    • 查詢參數(Query parameters)
    • 請求本文(Request body)

http://localhost:8000/users/? [email protected]

  • :8000:連接埠號。FastAPI 預設使用 8000。
  • /users/:要存取的端點路徑。
  • ?:查詢參數的開始。
  • `[email protected]`:查詢參數。此處將電子郵件傳給端點。
使用 FastAPI 將 AI 佈署到生產環境

回應結構

  • API 回傳給用戶端的資料
    • 含使用者資訊的 JSON 回應負載
  • 通常包含:
    • 狀態碼(200 OK、404 Not Found 等)
    • 標頭(Headers)
    • 回應本文(請求的資料或操作結果)
HTTP/1.1 200 OK
date: Fri, 18 Oct 2024 12:34:56 GMT
server: uvicorn
content-length: 76
content-type: application/json

{
  "username": "johndoe",
  "email": "[email protected]",
  "age": 30
}
使用 FastAPI 將 AI 佈署到生產環境

Pydantic 模型

  • 建立 User
  • 使用 Pydantic
from pydantic import BaseModel
class User(BaseModel):
    username: str
    email: str
    age: int
  • 繼承自 BaseModel
  • 以型別註記定義屬性
  • 依型別自動驗證
使用 FastAPI 將 AI 佈署到生產環境

驗證錯誤

from pydantic import ValidationError
try:
    invalid_user = User(username="john_doe", email="[email protected]", 
                        age="thirty")
    print("Invalid User:", invalid_user)
except ValidationError as e:
    print("Validation Error:", e)
Validation Error: 1 validation error for User age
Input should be a valid integer, unable to parse string as an integer 
[type=int_parsing, input_value='thirty', input_type=str]
使用 FastAPI 將 AI 佈署到生產環境

在 FastAPI 中使用 Pydantic 模型

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class User(BaseModel): username: str email: str age: int
@app.post("/users", response_model=User)
async def create_user(user: User): return user
  • 模型用作 response_model
  • 模型作為參數型別提示
  • 請求自動驗證
  • 請求/回應的序列化與反序列化
  • 產生 API 文件
使用 FastAPI 將 AI 佈署到生產環境

請求與回應格式

curl -X 'POST' \
  'http://localhost:8000/users/' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
  }'

 

{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
}
使用 FastAPI 將 AI 佈署到生產環境

一起來練習吧!

使用 FastAPI 將 AI 佈署到生產環境

Preparing Video For Download...