如何在OpenAPI 3.0响应中排除或替换privateinfo的uniq_id字段?
问题与解决方案
问题背景
我用OpenAPI 3.0 YAML生成处理REST请求的Java代码,当前YAML片段如下:
openapi: 3.0.3 info: title: OpenAPI definition version: v0 paths: /users/get-user-by-name: get: tags: - user-controller operationId: getUser parameters: - name: username in: query required: true schema: type: string responses: 200: description: OK content: application/json: schema: $ref: '#/components/schemas/User' components: schemas: privateinfo: type: object properties: connection: type: string user_id: type: string isSocial: type: boolean uniq_id: type: string required: - connection - user_id - isSocial User: type: object properties: username: type: string email: type: string email_verified: type: boolean user_id: type: string name: type: string privateinfo: type: array items: $ref: '#/components/schemas/privateinfo'
试了加required:字段没用,现在要解决两个问题:
- 怎么让
/users/get-user-by-name接口的响应体里不出现uniq_id字段? - 如果没法排除,能不能不改动Java代码,直接让这个字段的值固定是"NA"?
解决方法
一、排除响应里的uniq_id字段
不用修改原有的privateinfo Schema,直接在接口的响应定义里重新写一个只包含需要字段的结构就行,具体改法如下:
responses: 200: description: OK content: application/json: schema: type: object properties: username: type: string email: type: string email_verified: type: boolean user_id: type: string name: type: string privateinfo: type: array items: type: object properties: connection: type: string user_id: type: string isSocial: type: boolean required: - connection - user_id - isSocial
这种方法兼容性最好,所有主流的OpenAPI代码生成器都支持。
另外也可以用allOf加not关键字,但有些生成器对not支持不好,不推荐:
responses: 200: description: OK content: application/json: schema: allOf: - $ref: '#/components/schemas/User' not: properties: privateinfo: items: properties: uniq_id: {}
二、给uniq_id设置默认值"NA"
如果不能排除字段,直接在privateinfo的Schema里给uniq_id加个default属性,生成Java代码时会自动把这个默认值带到实体类里,不用手动改代码:
privateinfo: type: object properties: connection: type: string user_id: type: string isSocial: type: boolean uniq_id: type: string default: "NA" # 加这个默认值配置 required: - connection - user_id - isSocial
这样返回的响应里,uniq_id就会默认显示"NA"。
内容的提问来源于stack exchange,提问作者madD7
相关产品推荐
相关产品推荐

