0%

FastAPI自学教程(76) - 客户端代码生成机制

1.基础原理

1
2
3
4
5
6
7
8
9
10
11
12
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
price: float

@app.post("/items/")
async def create_item(item: Item):
return {"message": "item received"}
  • FastAPI基于OpenAPI规范自动生成API文档和数据结构模型
  • 生成机制流程:
    graph TD
      A[定义Pydantic模型] --> B[生成OpenAPI规范]
      B --> C{客户端生成工具}
      C --> D[TypeScript客户端]
      C --> E[其他语言客户端]

2.TypeScript客户端生成

2.1 安装与配置

1
npm install @hey-api/openapi-ts --save-dev
1
2
3
4
5
{
"scripts": {
"generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios"
}
}
  • 使用openapi-ts工具生成基于axios的客户端
  • 支持自动类型推导和API路径映射

2.2 客户端使用示例

1
2
3
4
5
6
7
8
9
10
import { createItem, getItems } from './src/client';

async function addItem() {
try {
const response = await createItem({ name: "Laptop", price: 1299 });
console.log(response.data.message); // "item received"
} catch (error) {
console.error("API Error:", error);
}
}
  • 自动生成的方法支持Promise异步调用
  • 编辑器可智能提示请求参数和响应结构

3.多语言生成方案

工具名称 支持语言 核心特性
OpenAPI Generator 50+种语言 支持模板定制,社区活跃
fastapi-client Python/TS 原生支持FastAPI特性
Swagger Codegen Java/Go等 企业级支持,生成完整SDK

4.生产环境建议

  1. 版本控制
    • 将openapi.json纳入版本管理,确保客户端与API版本同步
  2. 安全校验
    1
    app = FastAPI(openapi_url="/api/v1/openapi.json")
    限制OpenAPI端点访问权限
  3. 持续集成
    1
    2
    3
    # GitHub Actions配置示例
    - name: Generate Client
    run: npm run generate-client
    在CI流程中自动生成客户端
  4. 性能优化
    • 对高频接口生成gRPC客户端替代REST

测试命令示例:

1
2
3
4
5
# 生成TypeScript客户端
npm run generate-client

# 运行FastAPI服务
uvicorn main:app --reload