Fetching Questions

As we discussed above, we'll be using the Open Trivia DB API to get the questions. Head over to their API, select the number of questions, category, and difficulty. The question type should be Multiple Choice and the encoding should be Default Encoding. Click on Generate API URL and you'll get an API URL. 

Sample API URL: https://opentdb.com/api.php?amount=10&type=multiple

For fetching the questions, we'll be using requests module. It can be installed as:

$ pip install requests

Let's create a Python file quiz_data.py to fetch the quiz questions and answers using the API URL generated above.

import requests

parameters = {
    "amount": 10,
    "type": "multiple"
}

response = requests.get(url="https://opentdb.com/api.php", params=parameters)
question_data = response.json()["results"]
In the above script, instead of directly adding the amount and type parameters in the URL, we have created a parameters dictionary and added the respective values. After that, we're making a GET request using requests library on the Open Trivia DB API URL. A sample JSON response looks like this:
{
  "response_code": 0,
  "results": [
    {
      "category": "Entertainment: Video Games",
      "type": "multiple",
      "difficulty": "hard",
      "question": "What was the name of the hero in the 80s animated video game 'Dragon's Lair'?",
      "correct_answer": "Dirk the Daring",
      "incorrect_answers": ["Arthur", "Sir Toby Belch", "Guy of Gisbourne"]
    },
    {
      "category": "Entertainment: Video Games",
      "type": "multiple",
      "difficulty": "medium",
      "question": "Which of these game franchises were made by Namco?",
      "correct_answer": "Tekken",
      "incorrect_answers": ["Street Fighter", "Mortal Kombat", "Dragon Quest"]
    }
  ]
}
 

The JSON data contains a dictionary with two keys - response_code and results. The response_code tells developers what the API is doing. The results is a list we are interested in. So, we have stored the value of results in a variable question_data.

Discussion

3

0