Swagger 正文参数返回 400“额外表单数据参数名称不在规范中”


通过

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 编辑器中进行验证,但运行发送请求会给出

ERROR Method Not Allowed
Headers
undefined
Body

将 addProduct(( 的返回更改为

'Product Added', 200  

仍然返回 400,因此问题显然在连接级别。

非常感谢

已解决。

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

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

返回 200

Python 字典用于发送表单数据;正文数据需要以 JSON 字符串的形式发送。

相关内容

  • 没有找到相关文章

最新更新