0

I am currently on a Discord Bot interacting with the Controlpanel API. (https://documenter.getpostman.com/view/9044962/TzY69ub2#02b8da43-ab01-487d-b2f5-5f8699b509cd)

Now, I am getting an KeyError when listing a specific user.

headers = {
    'Accept': 'application/json',
    'Authorization': 'Bearer <censored>'
}

url = "https://<censored>"
endpoint = f"/api/users/{user}"

if __name__ == '__main__':
    data = requests.get(f'{url}{endpoint}', headers=headers).text
    for user in json.loads(data)['data']:
        embed = discord.Embed(title="Users")
        embed.add_field(name=user['id'], value=user['name'])
        await ctx.send(embed=embed)

^That's python.

Error:

for user in json.loads(data)['data']:

KeyError: 'data'

How can I fix this?

Thank you!

unrexx
  • 1
  • 1
  • Print out the dictionary from the output json.loads(data). Does it have the data key? – VRComp Jan 11 '22 at 14:49
  • There is no 'data' key in your json.loads(data) because your code is correct – Ronan Jan 11 '22 at 14:52
  • Does this answer your question? [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – Ulrich Eckhardt Jan 11 '22 at 16:10
  • `Response` objects from `requests` have a `json` method that will return a python object. You don't need to do it manually. – Speedlulu Jan 11 '22 at 18:02

2 Answers2

1

This KeyError happens usually when the Key doesn't exist(not exist or even a typo). in your case I think you dont have the 'data' key in your response and your should use something like:

data.json()

if you can post the complete response it would be more convinient to give you some hints.

araz malek
  • 21
  • 4
0

The endpoint you're hitting does not return a list but a single object.

You should use the generic endpoint : {{url}}/api/users

Also I don't think you want to recreate your embed object for each user.

headers = {
    'Authorization': 'Bearer <censored>'
}

url = 'https://<censored>'
endpoint = '/api/users'

if __name__ == '__main__':
    embed = discord.Embed(title="Users")
    for user in requests.get(
        f'{url}{endpoint}', headers=headers
    ).json()['data']:
        embed.add_field(name=user['id'], value=user['name'])
        await ctx.send(embed=embed)

Also I'm pretty sure you can't just await like that in __main__.

Speedlulu
  • 331
  • 2
  • 7