我正在尝试制作尽可能简单的 REST API 服务器和客户端,服务器和客户端都是用 Python 编写并在同一台计算机上运行。
从本教程:
https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
我将其用于服务器:
# server.py
from flask import Flask, jsonify
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
if __name__ == '__main__':
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
如果我从命令行运行此命令:
curl -i http://localhost:5000/todo/api/v1.0/tasks
Run Code Online (Sandbox Code Playgroud)
我明白了:
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 317
Server: Werkzeug/0.16.0 Python/3.6.9
Date: Thu, 05 Mar 2020 02:45:59 GMT
{
"tasks": [
{
"description": "Milk, Cheese, Pizza, Fruit, Tylenol",
"done": false,
"id": 1,
"title": "Buy groceries"
},
{
"description": "Need to find a good Python tutorial on the web",
"done": false,
"id": 2,
"title": "Learn Python"
}
]
}
Run Code Online (Sandbox Code Playgroud)
太好了,现在我的问题是,如何使用请求来编写 Python 脚本来获取相同的信息?
我怀疑这是正确的想法:
# client.py
import requests
url = 'http://todo/api/v1.0/tasks'
response = requests.get(url,
# what goes here ??
)
print('response = ' + str(response))
Run Code Online (Sandbox Code Playgroud)
然而,正如您从我的评论中看到的,我不确定如何设置requests.get.
我尝试使用这个SO帖子:
作为指导,但尚不清楚如何根据消息更改调整格式。
能否提供有关如何设置要传递的参数的简要说明requests.get,并建议必要的更改以使上面的客户端示例正常工作?谢谢!
- - 编辑 - -
我还可以提到的是,我让客户端非常轻松地使用 Postman 工作,我只是不确定如何在 Python 中设置语法:
- - 编辑 - -
根据下面的 Icedwater 响应,这是为客户提供的完整的工作代码:
# client.py
import requests
import json
url = 'http://localhost:5000/todo/api/v1.0/tasks'
response = requests.get(url)
print(str(response))
print('')
print(json.dumps(response.json(), indent=4))
Run Code Online (Sandbox Code Playgroud)
结果:
<Response [200]>
{
"tasks": [
{
"description": "Milk, Cheese, Pizza, Fruit, Tylenol",
"done": false,
"id": 1,
"title": "Buy groceries"
},
{
"description": "Need to find a good Python tutorial on the web",
"done": false,
"id": 2,
"title": "Learn Python"
}
]
}
Run Code Online (Sandbox Code Playgroud)
从help(requests.get):
Help on function get in module requests.api:
get(url, params=None, **kwargs)
Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Run Code Online (Sandbox Code Playgroud)
所以我想说requests.get(url)这足以得到回应。然后根据 API 预期返回的内容查看json()或data()函数。response
因此,对于 JSON 响应的情况,以下代码应该足够了:
import requests
import json
url = "https://postman-echo.com/get?testprop=testval"
response = requests.get(url)
print(json.dumps(response.json(), indent=4))
Run Code Online (Sandbox Code Playgroud)
使用实际的测试 API 尝试上面的代码。