Home > Enterprise >  Extracting element from API
Extracting element from API

Time:09-16

How do I extract an Element from an API .. The API looks something like

{"response_code":0,"results":[{"category":"General Knowledge","type":"multiple","difficulty":"hard","question":"Electronic music producer Kygo's popularity skyrocketed after a certain remix. Which song did he remix?","correct_answer":"Ed Sheeran - I See Fire","incorrect_answers":["Marvin Gaye - Sexual Healing","Coldplay - Midnight","a-ha - Take On Me"]}]}

    async with aiohttp.ClientSession() as session:
     request = await session.get('https://opentdb.com/api.php?amount=1&category=9&difficulty=hard')
     questionjson = await request.json()
     request2 = await session.get('https://opentdb.com/api.php?amount=1&category=9&difficulty=hard')
     
     questionjson1 = str(questionjson['results'])
     
    
     embed = discord.Embed(title="**__Trivia Time !!__**",description = questionjson1['question'] ,color=  random.choice(colors))```

And I only want to extract the “question” element from that api  

CodePudding user response:

So I played with the API and here you go :-

@bot.command()
async def trivia(ctx):
  async with aiohttp.ClientSession() as cs:
    async with cs.get('https://opentdb.com/api.php?amount=1&category=9&difficulty=hard') as r:
      res = await r.json()
      print(res)
      question = res['results'][0]['question'] #This line gets the question
      embed = discord.Embed(title="**__Trivia Time !!__**",description = question ,color=ctx.author.color)
      await ctx.send(embed=embed)
  • Related