Skip to content

Instantly share code, notes, and snippets.

@matheusjardimb
Created May 15, 2024 00:42
Show Gist options
  • Save matheusjardimb/9c35ea76d2704d90e5bc428c042065e9 to your computer and use it in GitHub Desktop.
Save matheusjardimb/9c35ea76d2704d90e5bc428c042065e9 to your computer and use it in GitHub Desktop.
Get quiz questions from opentdb's API (programming class exercise)
def get_questions(amount: int = 10, difficulty: str = 'easy') -> dict:
import http.client
import json
conn = http.client.HTTPSConnection("opentdb.com")
conn.request("GET", f"/api.php?amount={amount}&difficulty={difficulty}&type=multiple")
response = conn.getresponse()
response_text = response.read().decode()
conn.close()
return json.loads(response_text)
def get_questions_alternative(amount: int = 10, difficulty: str = 'easy') -> dict:
"""
Alternative method, using requests, which needs to be installed with:
pip install requests
"""
import requests
req = requests.get(f'https://opentdb.com/api.php?amount={amount}&difficulty={difficulty}&type=multiple')
return req.json()
print(get_questions())
print(get_questions_alternative())
@matheusjardimb
Copy link
Author

The following may be useful for displaying questions properly:

def parse_text(html_string: str) -> str:
    import html
    # Convert HTML entity to regular single quote
    return html.unescape(html_string)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment