使用 requests 包发送 JSON
就像您可以从 API 响应中接收 JSON 文本一样,您也可以通过 POST 或 PUT 请求向 API 发送 JSON 文本。如果在 request.post() 和 request.put() 方法中使用 json 参数,requests 库会自动为您添加所需的请求头并完成编码。很方便!
我们来试一试!您知道吗?使用对 /playlists API 的 POST 请求,您可以一次性创建多个播放列表。
只需向 API 传入一个播放列表数组(每个包含一个 Name 属性),它就会一次性创建所有播放列表。
本练习是课程的一部分
Python 中的 API 入门
练习说明
- 将变量
playlists作为参数传给requests.post()方法,使其以 JSON 格式自动发送。 - 从 API 获取所有播放列表的列表。
- 通过打印 JSON 文本来检查该 GET 请求的响应。
交互式实操练习
通过完成这段示例代码来试试这个练习。
playlists = [{"Name":"Rock ballads"}, {"Name":"My favorite songs"}, {"Name":"Road Trip"}]
# POST the playlists array to the API using the json argument
requests.post('http://localhost:3000/playlists/', ____=____)
# Get the list of all created playlists
response = requests.____('http://localhost:3000/playlists')
# Print the response text to inspect the JSON text
print(response.____)