Files
lab_riddles/api.py
njmason22 e1cd7b7c87 api.py
2026-02-13 20:49:53 -05:00

67 lines
2.3 KiB
Python

# RiddleAPI
# ---------
# By Chris Proctor
# The Riddle API takes care of connecting to the server.
import requests
from random import choice
class APIError(Exception):
"A custom error we'll use when something goes wrong with the API"
class RiddleAPI:
"Provides an easy way for Python programs to interact with a Riddle Server"
def __init__(self, server_url):
self.server_url = server_url
def get_all_riddles(self):
"Fetches all the riddles from the server"
route = "/all"
response = requests.get(self.server_url + route)
if response.ok:
return response.json()['riddles']
else:
raise APIError(response.json()['errors'])
def guess_riddle(self, riddle_id, guess):
"Submits a guess to the server. Returns True or False"
route = "/guess"
params = {'id': riddle_id, 'answer': guess}
response = requests.post(self.server_url + route, json=params)
if response.ok:
return response.json()
else:
raise APIError(response.json()['errors'])
def get_riddle(self, riddle_id):
"Fetches a single riddle from the server"
route = "/show"
params = {'id': riddle_id}
response = requests.get(self.server_url + route, json=params)
if response.ok:
return response.json()
else:
raise APIError(response.json()['errors'])
# raise NotImplementedError("The API doesn't support `get_riddle` yet. Can you add it?")
def get_random_riddle(self):
"Fetches all riddles from the server and then randomly returns one"
riddle_list = self.get_all_riddles() # calls another method and assigns it to a variable
#print(f"DEBUG: {choice(riddle_list)}") # displays in debug-mode as a dict
return choice(riddle_list) # the choice method randomizes the variable
def add_riddle(self, question, answer):
"Adds a new riddle to the server"
route = "/new"
params = {'question': question, 'answer': answer}
response = requests.post(self.server_url + route, json=params)
if response.ok:
return response.json()
else:
raise APIError(response.json()['errors'])