如何为响应模型添加多语言 example 并在 Swagger 切换?

解读

面试官想确认三件事:

  1. 你是否知道 FastAPI 的 example 字段本质上是 OpenAPI 的 example,只能写死一份;
  2. 你是否能在“只能写一份 example”的限制下,用运行时逻辑把多语言数据动态塞给前端;
  3. 你是否清楚 Swagger-UI 的 locale 切换只是界面语言,并不会自动帮你换 example,需要你自己在接口层做“语言路由”。

国内项目普遍要同时支持中、英,有时还要繁体或少数民族语言,面试时如果只说“用 i18n 库”却讲不清怎么落到 Swagger 里,会被认为“只背了八股”。

知识点

  1. Pydantic 的 Field(example=...) 或 Config.schema_extra 只能声明静态 example,运行期无法改。
  2. FastAPI 的 /docs 实际是 Swagger-UI,界面语言由查询参数 ?lang=zh-CN 或 ?lang=en-US 控制,与接口返回值无关。
  3. 想让同一个接口在 Swagger 里出现“中文 example / 英文 example”两种预览,只能注册两条路径(或两个 router),用相同的 Python 函数,不同的 response_model。
  4. 运行时多语言返回靠请求头 Accept-Language,与 Swagger example 无关;二者不要混淆。
  5. 国内上线规范要求“接口文档必须可切换中文/英文 example”,所以必须给出“文档层”方案,而不是“响应层”方案。

答案

步骤一:定义两个响应模型,仅 example 不同

from pydantic import BaseModel, Field

class UserOutZh(BaseModel):
    id: int = Field(example=1)
    name: str = Field(example="张三")
    motto: str = Field(example="你好,世界")

    class Config:
        schema_extra = {"example": {"id": 1, "name": "张三", "motto": "你好,世界"}}

class UserOutEn(BaseModel):
    id: int = Field(example=1)
    name: str = Field(example="Alice")
    motto: str = Field(example="Hello, world")

    class Config:
        schema_extra = {"example": {"id": 1, "name": "Alice", "motto": "Hello, world"}}

步骤二:同一个业务函数,挂两条路径,分别指定不同的 response_model

from fastapi import FastAPI, Path

app = FastAPI(title="多语言 Demo")

async def read_user(uid: int = Path(...)):
    # 真实场景这里根据 Accept-Language 返回不同语言
    return {"id": uid, "name": "张三", "motto": "你好,世界"}

app.add_api_route("/users/zh/{uid}", read_user, response_model=UserOutZh, tags=["中文示例"])
app.add_api_route("/users/en/{uid}", read_user, response_model=UserOutEn, tags=["English Example"])

步骤三:访问文档

  • /docs?lang=zh-CN 默认展开“中文示例”分组,看到的 example 是张三;
  • 点右上语言框切到 English,再展开“English Example”分组,看到的 example 是 Alice。

这样就满足了“在 Swagger 切换语言同时看到对应 example”的国内文档合规要求。

拓展思考

  1. 如果接口太多,手写双份模型会爆炸,可以写一个工厂函数,利用 create_model 动态生成带不同 example 的模型,再批量 add_api_route。
  2. 真正的运行时多语言不要依赖路径,而是在业务层读 Accept-Language,用 gettext 或 i18next 做消息替换,与 Swagger example 完全解耦。
  3. 国内银行、证券项目还要求“示例值必须脱敏”,可以把 example 抽成 JSON 文件,由 Sphinx 或 MkDocs 统一渲染,FastAPI 侧只留 $ref,通过 CICD 注入不同语言版本,实现“文档自动化合规”。