swagger Openapi 3.0和支持GET和POST的端点

1l5u6lss  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(292)

我有一个手工制作的REST API,我想改进它以使用Openapi 3.0.0
我的一个(手工制作的Python/Flask)端点同时支持GET和POST方法:

@app.route('/search', methods=['POST','GET'])
def searchDevices():

    if request.method == 'GET':
        brand = request.args.get('brand')
        model = request.args.get('model')
        capas = request.args.get('capabilities')
    elif request.method == 'POST':
        brand = request.form.get('brand')
        model = request.form.get('model')
        capas = request.form.get('capabilities')

有没有办法在Openapi 3.0.0中对此进行建模呢?现在我知道我需要用很多重复来定义YAML端点(再见,干),但也许我遗漏了一些东西。如果我能做这样的事情就太酷了:

paths:
  /search:
    parameters:
      - schema:
         :
    get, post:

但可惜的是,这似乎不工作的时刻。

2izufjch

2izufjch1#

一个终结点,无论参数是通过GET还是POST方法发送的,它都支持这些参数。
这可以用OpenAPI建模,但需要一些重复,因为:a)不同的HTTP方法(GET、POST等)必须被定义为单独的操作; B)查询字符串和请求主体由不同的关键字表示。
要对GET查询字符串重用POST请求主体架构,需要将整个查询字符串定义为单个对象类型参数,并使用style: form + explode: true作为序列化样式。这意味着在查询字符串中发送对象时,该对象将转换为key=value对。
API定义如下所示:

openapi: 3.0.3
...

paths:
  /search:
    get:
      parameters:
        - in: query
          name: params  # Arbitrary name, not used in the request URL
          schema:
            $ref: '#/components/schemas/SearchParams'

          # This is the default serialization style for query parameters
          # so these keywords can be omitted
          style: form
          explode: true
      responses:
        '200':
          description: OK
    post:
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SearchParams'
      responses:
        '200':
          description: OK

components:
  schemas:
    SearchParams:
      type: object
      properties:
        brand:
          type: string
        model:
          type: string
        capabilities:
          type: string

相关问题