如何解析来自 Digital Ocean API 的 JSON 数据

How to parse JSON data from Digital Ocean API

你好,我正在尝试从 Digital Ocean API 构建一个应用程序,所以基本上我正在使用请求库 (Python) 向 https://api.digitalocean.com/v2/droplets 发送请求,这是我的代码

import requests
host = "https://api.digitalocean.com"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer MYTOKEN"
    }
dataa = {}
api = requests.post(f"{host}/v2/droplets", headers= headers, data=json.dumps(dataa))

然后尝试通过 data = api.json() 访问 API 返回的信息 如果我尝试通过 运行 print(data['droplet']['id']) 打印 id 我 运行 到这个错误

Traceback (most recent call last):
  File "/home/gogamic/code/gogamic-website/functions.py", line 276, in <module>
    create_new_server('mai@gogamic.com', 2)
  File "/home/gogamic/code/gogamic-website/functions.py", line 260, in create_new_server
    server_info = json.loads(infoo.json())
  File "/usr/lib/python3/dist-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 525, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是从 API

返回的 JSON

API 方法是 GET 而不是 POST:

https://developers.digitalocean.com/documentation/v2/#list-all-droplets

你的代码适用于我替换:

api = requests.post(f"{host}/v2/droplets",
                    headers= headers,
                    data=json.dumps(dataa))

与:

api = requests.get(f"{host}/v2/droplets",
                    headers= headers,
                    data=json.dumps(dataa))

并且根据@fixatd 添加:

print(api)

产量:

<Response [200]>

NOTE I have no droplets to list.

为了完整性,创建一个 droplet 并重新运行:

doctl compute droplet create Whosebug-65092533 \
--region sfo3 \
--size s-1vcpu-2gb \
--ssh-keys ${KEY} \
--tag-names Whosebug \
--image ubuntu-20-10-x64

然后:

使用:

content = resp.json()

if resp.status_code != 200:
    print("Unexpected status code: {}".format(resp.status_code))
    quit()

for droplet in content["droplets"]:
    print("ID: {}\tName: {}".format(droplet["id"], droplet["name"]))

产量:

ID: 219375538   Name: Whosebug-65092533