How would I put a API's output into different variables in Python?

Question:

So I am using a riddle API and whenever it is ran it outputs it data like this:

  [
  {
    "title": "The Magic House",
    "question": "There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of house is that?",
    "answer": "bathroom"
  }
  ]

How could I convert the title, question and answer from the API output into 3 different variables that could then be used in a program.

If the API outputs that the Title =A ,the question = B, and answer = C ,then how would I make it so that in my code, Variable1=A,Variable2=B and Variable3=C?

The API comes from API ninjas and here is the code provided with it:

import requests

api_url = 'https://api.api-ninjas.com/v1/riddles'
response = requests.get(api_url, headers={'X-Api-Key': 'YOUR_API_KEY'})
if response.status_code == requests.codes.ok:
    print(response.text)
else:
    print("Error:", response.status_code, response.text)

How would I do this with the code provided?

Asked By: turtlesXD

||

Answers:

The response you received from the server looks like JSON so use json module to parse it. When you parse the response, you access the items like normal python list/dict:

import json

response_text = """[
  {
    "title": "The Magic House",
    "question": "There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of house is that?",
    "answer": "bathroom"
  }
]"""

data = json.loads(response_text)

for item in data:
    print("Title =", item["title"])
    print("Question =", item["question"])
    print("Answer =", item["answer"])

print(data)

Prints:

Title = The Magic House
Question = There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of house is that?
Answer = bathroom
Answered By: Andrej Kesely