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!
CodePudding user response:
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.
CodePudding user response:
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__.
