请求与响应模型

使用 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

Passons à la pratique !

使用 FastAPI 在生产环境中部署 AI

Preparing Video For Download...