-2

I am making a discord bot that is meant to send embeds with images gotten froms APIs. I have one for a dog, and it works. The code for the dog one:

if message.content.lower().startswith("!dog"):
    async with aiohttp.ClientSession() as session:
       request = await session.get('https://some-random-api.ml/img/dog') # Make a request
       dogjson = await request.json() # Convert it to a JSON dictionary
    dogembed = discord.Embed(title="Doggy!", color=discord.Color.blue()) 
    dogembed.set_image(url=dogjson['link'])
    

await message.channel.send(embed=dogembed)

This works perfectly, and always. However when I try to do the same thing for a cat images, using "https://api.thecatapi.com/v1/images/search" I get this error.

Error

Here is my code for the cat one:

if message.content.lower().startswith("!cat"):
    async with aiohttp.ClientSession() as session:
       request = await session.get('https://api.thecatapi.com/v1/images/search') # Make a request
       catjson = await request.json() # Convert it to a JSON dictionary
    Catembed = discord.Embed(title="Kitty!", color=discord.Color.blue()) 
    Catembed.set_image(url=catjson['link'])
    
    await message.channel.send(embed=Catembed)

Please help me with this, I am a beginner to python and APIs.

Balaji
  • 795
  • 1
  • 2
  • 10
Martin
  • 158
  • 1
  • 3
  • 13
  • The only difference I see in your two code, is the await in the cat one is tabbed over, try tabbing it on line with the if statement – troy Nov 05 '21 at 16:50
  • Sorry that was a mistake in the code here, the dog one is like that too, and if i move them over it gives an error. – Martin Nov 05 '21 at 17:12

1 Answers1

2

If you take a look at the result of your API call you'll see that it's a list, not a dictionary, as your error also suggests.

[
  {
    "breeds": [],
    "id": "992",
    "url": "https://cdn2.thecatapi.com/images/992.jpg",
    "width": 560,
    "height": 368
  }
]

This means that you can't do catjson['link'], but you first have to take the first element of the list out of it and then access that field.

catjson[0]['link']

Further, as you can see from the snippet I pasted above, link doesn't exist as a field in that API response. You're looking for url.

catjson[0]['url']

For future reference, it never hurts to look at the output of the API (either in your browser or by printing the result) before trying to use it, and also while debugging. If you get an error that a field doesn't exist, take a look at which fields do exist.

The reason it works fine for the dog API is because the response looks completely different, which is to be expected when using two entirely different API's.

stijndcl
  • 5,294
  • 1
  • 9
  • 23