Flask API failing to decode JSON data. Error: "message": "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"

Flask API failing to decode JSON data. Error: "message": "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"

我正在使用 flask 和 flask-restful 设置一个简单的休息 api。现在我要做的就是用一些 Json 数据创建一个 post 请求,然后 return 它只是为了看看它是否有效。我总是得到同样的错误 "message": "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"

下面是我的代码

from flask import Flask, jsonify, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)


class Tester(Resource):
   def get(self):
       return {'about': 'Hello World'}

   def post(self):
       data_json = request.get_json(force=True)
       return {'you sent': data_json}


api.add_resource(Tester, '/')

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

下面是我用来测试的 curl 请求,我也尝试过使用 postman

发出请求
curl -H "Content-Type: application/json" -X POST -d '{'username':"abc",'password':"abc"}' http://localhost:5000

curl 请求(负载)不正确。在负载中使用双引号。

curl -H "Content-Type: application/json" -X POST -d '{"username":"abc","password":"abc"}' http://localhost:5000

你需要像这样在 Postman 中 select raw -> JSON (application/json):

当涉及到您的 cURL 请求时, 解释说 windows 的命令行不支持带单引号的字符串,因此请使用:

curl -i -H "Content-Type: application/json" -X POST -d "{\"username\":\"abc\", \"password\":\"abc\"}" 127.0.0.1:5000

改为:

curl -H "Content-Type: application/json" -X POST -d '{'username':"abc",'password':"abc"}' http://localhost:5000

\ 转义 " 个字符。

您还需要启用 Content-Length header。

一些额外的信息,以防你像我一样使用 python 脚本来测试你的烧瓶 api - 你必须 dumps 在将字典添加到数据字段之前。

import requests
import json

response = requests.post(
    'http://localhost:5000', 
    data = json.dumps({'username':"abc",'password':"abc"}),
    headers = {"Content-Type": "application/json"}
    )