You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置openapi-generator-cli在Pydantic模型中包含示例

解决OpenAPI Generator生成Pydantic模型时添加自定义示例的问题

问题根源

你修改模板后出现重复Field,是因为原模板已默认生成不带示例的Field语句,新增的模板代码又重复生成了一次;示例值错误则是因为模板未正确关联你定义的examples数组,误用了默认占位值。

正确的模板修改步骤

  1. 定位原模板核心逻辑
    原model_generic.mustache模板中,字段的默认生成逻辑大致如下(不同版本细节略有差异):

    {{name}}: {{{vendorExtensions.x-py-typing}}} = Field({{#description}}"{{{description}}}"{{/description}})
    

    需要直接修改这段逻辑,而非新增重复的Field代码。

  2. 替换为带示例的模板代码
    将字段生成部分替换为以下内容,同时兼容example(单个示例)和examples(多示例取第一个)的场景,避免重复生成Field:

    {{#vars}}
    {{name}}: {{{vendorExtensions.x-py-typing}}} = Field(
        {{#description}}description="{{{description}}}"{{/description}}
        {{#or example examples}}
            {{#description}}, {{/description}}
            {{#example}}
                example={{#isString}}"{{{example}}}"{{/isString}}{{^isString}}{{{example}}}{{/isString}}
            {{/example}}
            {{#examples}}
                {{#-first}}
                    example={{#isString}}"{{{.}}}"{{/isString}}{{^isString}}{{{.}}}{{/isString}}
                {{/-first}}
            {{/examples}}
        {{/or}}
    )
    {{/vars}}
    

    这段代码的逻辑:

    • 仅生成一次Field()语句
    • 优先使用example字段,无此字段则取examples数组的第一个元素
    • 自动处理字符串类型示例的引号包裹,非字符串类型直接输出值
  3. 验证生成结果
    使用修改后的模板重新生成,正确的Pydantic模型代码应为:

    class Algorithm(BaseModel):
        """
        Algorithm
        """ # noqa: E501
        id: StrictInt = Field(description="ID of the algorithm", example=1)
        project_id: StrictInt = Field(description="ID of the project", example=1)
    

额外注意事项

  • 确保OpenAPI Schema中examples为数组类型(如examples: [1]),模板通过{{#-first}}提取第一个元素
  • 若需支持多示例,可修改模板使用examples参数(Pydantic支持传入示例数组,不过单个示例更常用)
  • 模板中的isString是OpenAPI Generator内置变量,用于判断字段类型,确保示例值的引号格式正确

内容的提问来源于stack exchange,提问作者ArkanSaaS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 15:42:35