Raghav Mri
Raghav Mri

Reputation: 35

How to parse JSON data from Digital Ocean API

Hello there i am trying to build a App Out of Digital Ocean API so basically i am sending a request to https://api.digitalocean.com/v2/droplets using the requests library(Python) and here's my code

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))

And then try to access the info returned by API by data = api.json() and if i try to print the id by running print(data['droplet']['id']) i running onto this error

Traceback (most recent call last):
  File "/home/gogamic/code/gogamic-website/functions.py", line 276, in <module>
    create_new_server('[email protected]', 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)

This is the returned JSON From the API

Upvotes: 0

Views: 371

Answers (1)

DazWilkin
DazWilkin

Reputation: 40201

That API method is a GET not a POST:

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

Your code works for me replacing:

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

With:

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

And per @fixatd adding:

print(api)

Yields:

<Response [200]>

NOTE I have no droplets to list.

For completeness, create a droplet and re-run:

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

Then:

Using:

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"]))

Yields:

ID: 219375538   Name: stackoverflow-65092533

Upvotes: 1

Related Questions