Swagger Body参数返回400"额外的formData参数名称不在spec"

时间:2017-02-14 08:36:57

标签: python pycharm yaml swagger

通过Python-2.7,connexion&和发送身体参数时遇到问题Pycharm。

api.yaml

swagger: '2.0'
info:
  title: Products Api Backend
  version: "1.0.0"
consumes:
  - application/json
produces:
  - application/json
paths:
  /products:
    post:
      operationId: app.addProduct
      parameters:
      - name: body
        description: Product payload to add
        in: body
        required: true
        schema:
          $ref: '#/definitions/ProductParameters'
      responses:
        200:
          description: Data received and added correctly
          schema:
            type: string
definitions:
  ProductParameters:
    description: Needed attributes for each post request
    properties:
      name:
        type: string
        description: Product name

app.py

import connexion

api = connexion.api

def addProduct(name):
   return 'Product Added'   # or 'Product Added', 200

app = connexion.App(__name__)
app.add_api('api.yaml', strict_validation=True)

if __name__ == '__main__':
    app.run(port=8092, debug=True)

运行

r = requests.post(appUrl, data={'name':'Product title here'})
print r
print r.content

返回

<Response [400]>
{
  "detail": "Extra formData parameter(s) name not in spec", 
  "status": 400, 
  "title": null, 
  "type": "about:blank"
}

YAML在Swagger Editor中验证,但正在运行发送请求

ERROR Method Not Allowed
Headers
undefined
Body

更改addProduct()返回

'Product Added', 200  

仍然返回400,所以问题显然在连接层面。

非常感谢

1 个答案:

答案 0 :(得分:0)

解决。

我忘了将Python字典变成字符串(对于正文),所以

import json
dataDict = {'name':'Product title here'}
dataStr = json.dumps(dataDict)
r = requests.post(appUrl, data=dataStr)

返回200

Python字典用于发送表单数据;正文数据需要作为JSON字符串发送。