如何在OpenAPI中使用components创建示例?示例显示为$ref未渲染
OpenAPI示例$ref未渲染问题解决办法
你遇到的问题是响应示例里的$ref没有被解析,而是直接显示引用字符串,核心原因是在响应的example字段中错误地将$ref嵌套在了deduction_charge键下,OpenAPI解析器只会识别直接作为字段值的$ref,嵌套结构会被当成普通JSON内容处理。
修正后的响应配置
responses: '200': description: Successful response content: application/json: schema: $ref: '#/components/schemas/deduction_charge' example: $ref: '#/components/examples/deduction_charge'
保持原components配置不变
components: examples: deduction_charge: summary: Example deduction charge value: deduction_charge: - id: "ct_h5e599d3-0000-4d46-9a52-1a37e7b5b8ef" status: "SUCCESS" description: "Super HD plan" amount: 10000 amount_refunded: 0 currency: "JPY" deduction_token: "dt_f5e599d3-8b9e-4d46-9a52-1a37e7b5b8ef" metadata: customerID: "123" customerName: "Yamada Taro" transactionID: "A123" created_at: "2023-11-07T15:30:00.000+09:00" updated_at: "2023-11-07T15:30:00.000+09:00"
为什么这样改?
你的components里已经定义了完整的示例结构(包含顶层deduction_charge键和数组内容),响应的example字段只需要直接引用这个组件即可。之前的嵌套写法会让解析器把$ref当成deduction_charge字段的普通值,而不是触发引用解析逻辑。
如果你的schema结构要求响应顶层就是deduction_charge数组,那当前的配置就能正确渲染出示例内容了。
内容的提问来源于stack exchange,提问作者vagavince
相关产品推荐
相关产品推荐

