【问题标题】:Flask - Get requests with json parameter using cURLFlask - 使用 cURL 获取带有 json 参数的请求
【发布时间】:2019-02-07 12:54:35
【问题描述】:

我使用 python 库flask 开发了一个简单的 REST API。这是我正在做的一个例子:

from flask import Flask, request
import json

app = Flask(__name__)

@app.route("/")
def hello():
    json_arg = json.loads(request.args.get("json_arg", None))
    non_json_arg = request.args.get("non_json_arg", None)
    return "Hello, your json arg is: %s and your non_json_arg is %s"%(json_arg, non_json_arg)


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

为了测试我的代码,我这样写了一个python客户端:

import requests
import json

json_arg = [
            {
                "0": 1.3,
                "1": 1.4
            },
            {
                "0": 5.3,
                "1": 40.5
            }
        ]
non_json_arg = "some_arg"

arguments = {
    "json_arg": json.dumps(json_arg),
    "non_json_arg": non_json_arg
}

r = requests.get("http://localhost:5000", params=arguments, headers={"content-type": "application/json"})

print(r.text)

这工作得很好,输出是:

Hello, your json arg is: [{u'1': 1.4, u'0': 1.3}, {u'1': 40.5, u'0': 5.3}] and your non_json_arg is some_arg

出于测试原因,我想用cURL做同样的事情,到目前为止我测试的是:

curl -X GET --data '{"json_arg": [ { "0": 1.3, "1": 1.4 }, { "0": 5.3, "1": 40.5 } ], "non_json_arg":"some_arg"}' http://localhost:5000

但这会返回错误:

....
>> json_arg = json.loads(request.args.get("json_arg", None))
TypeError: expected string or buffer

我已经测试了cURL 的许多其他论点,但我找不到这个简单问题的答案:

如何使用 json 参数向 API 发送 GET 请求?

【问题讨论】:

    标签: python rest api curl flask


    【解决方案1】:

    通常人们会为此使用 POST 请求而不是 get 请求。所以它看起来像这样:

    curl -X POST -d '{"json_arg": [ { "0": 1.3, "1": 1.4 }, { "0": 5.3, "1": 40.5 } ], "non_json_arg":"some_arg"}' http://localhost:5000
    

    但是,如果您确实想使用 GET 请求,则需要在实际 url 中使用参数,因此它看起来像:

    curl -X GET http://localhost:5000/?json_arg=%5B%7B%220%22%3A+1.3%2C+%221%22%3A+1.4%7D%2C+%7B%220%22%3A+5.3%2C+%221%22%3A+40.5%7D%5D&non_json_arg=some_arg
    

    我建议通常使用 POST 请求来发送 JSON 数据。

    【讨论】:

    • 对上述 api 的 curl 请求示例?
    • curl -X GET http://localhost:5000/?json_arg=%5B%7B%220%22%3A+1.3%2C+%221%22%3A+1.4%7D%2C+%7B%220%22%3A+5.3%2C+%221%22%3A+40.5%7D%5D&non_json_arg=some_arg
    • 您能否编辑您的问题以添加此评论,以便我接受答案?这将对其他人有所帮助:)
    猜你喜欢
    • 2014-02-15
    • 2018-02-18
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多