首页 > 解决方案 > 如何使用自定义分隔符序列化查询对象

问题描述

我有 yaml 文件:

openapi: 3.0.1
info:
  title: My API
  version: v1
paths:
  # /users;id=3;id=4?metadata=true
  /users:
    get:
      parameters:
        - in: query
          name: offset
          schema:
            type: integer
          description: The number of items to skip before starting to collect the result set
        - in: query
          name: limit
          schema:
            type: integer
          description: The numbers of items to return
        - in: query
          name: origin
          style: form
          explode: false
          schema:
            type: object
            properties:
              city:
                type: string
              zip:
                type: string
      responses:
        '200':
          description: A list of users

当我在https://editor.swagger.io中单击“执行”时,生成的 Curl 如下所示:

curl -X GET "https://editor.swagger.io/users?offset=2&limit=12&origin=city,atlanta,zip,303" -H "accept: */*"

但是,我需要它是这样的:

curl -X GET "https://editor.swagger.io/users?offset=2&limit=12&origin=city:atlanta|zip:303" -H "accept: */*"

是否有可能做到这一点?我在文档中找不到有关设置自定义分隔符的任何信息。

标签: swaggerswagger-uiopenapi

解决方案


简短的回答:

序列化参数未涵盖您的特定用例,它们遵循rfc6570 - 如果您想设计一个被广泛接受的 Web api,遵循标准是个好主意。

您指定explode: falsestyle:form。当你打开explode:true时,你会得到这个:

city=atlanta&zip=303

当您指定时,style:deepObject您将获得:

origin[city]=atlanta&origin[zip]=303

spaceDelimitedandpipeDelimited样式不适用于对象。

无模式工作

您当然可以在没有模式的情况下工作并定义origin类型的查询参数string。文档应该准确地解释你的期望,一个小例子将帮助人们使用你的 API。

我不会将该模式用于开放 API,但这可以作为内部 API 的解决方法。


推荐阅读