首页 文章

在swagger文档中使用对象类型查询参数

提问于
浏览
6

我有一个GET路由,我想在url中将对象参数编码为查询字符串 .

在编写swagger文档时,我基本上会遇到错误,不允许我在 query 类型参数中使用 schema / object 类型:

paths:
  /mypath/:
    get:
      parameters
        - in: path
          name: someParam
          description: some param that works
          required: true
          type: string
          format: timeuuid #good param, works well
        - $ref: "#/parameters/mySortingParam" #this yields an error

parameters:
  mySortingParam
    name: paging
    in: query
    description: Holds various paging attributes
    required: false
    schema:
      type: object
      properties:
        pageSize:
          type: number
        cursor:
          type: object
          properties:
            after:
              type: string
              format: string

具有对象值的请求查询参数将被编码在实际请求中 .

即使swagger在屏幕顶部显示错误,也会在swagger UI编辑器中正确呈现对象,但是错误会浮动在文档的顶部 .

3 回答

  • 2

    我不认为你可以在Swagger规范中使用"object"作为查询参数,因为查询参数只支持基本类型(https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types

  • 2

    现在可以使用OpenAPI 3.0 .

    parameters:
      - in: query
        name: values
        schema:
          type: object
          properties:
            genre_id: 
              type: integer
            author_id:
              type: integer
            title:
              type: string
          example:
           {
             "genre_id": 1,
             "author_id": 1
           }
        style: form
        explode: true
    

    在这里,您可以使用 styleexplode 关键字来指定参数的序列化方式 .

    • style定义多个值的分隔方式 . 可能的样式取决于参数位置 - 路径,查询, Headers 或cookie .

    • explode(true / false)指定数组和对象是否应为每个数组项或对象属性生成单独的参数 .

    对于上面的示例,网址将是:

    https://ebookstore.build/v1/users/books/search?genre_id=1&author_id=1
    

    有关使用OpenAPI v3和参数序列化描述参数的更多信息,请参阅here .

  • 8

    这是可能的,而不是OpenAPI 2.0 . OpenAPI 3.0描述了这是如何实现的:

    https://swagger.io/docs/specification/describing-parameters/

    parameters:
    - in: query
      name: filter
      # Wrap 'schema' into 'content.<media-type>'
      content:
        application/json:  # <---- media type indicates how to serialize / deserialize the parameter content
          schema:
            type: object
            properties:
              type:
                type: string
              color:
                type: string
    

    在此期间,您可以将查询参数作为普通旧字符串类型,然后手动执行序列化,然后根据需要设置查询参数 . 这是我在Swagger UI完全支持OpenAPI 3.0之前所做的事情 .

相关问题