Files
lab_riddles/api.py
caglazir2 2e80d30157 I submitted the changes I previously made during
Office Hours last week.

1. I use Steam regularly when I play games. I
would think that there are many webs of
POST and GET requests within that enable online
connections, downloading and saving game data etc.
I think the Steam client probably communicates
with the game servers with the POST and GET
requests to accompolish this.

2. Yeah I would say so! I didn't know about either
type of the requests before so I think I learned
about how things work. Very vaguely I knew that
anything we do on the Internetis basically an
endless transmission of data but I never
considered the technicality of transmissions
that take place.
2026-03-14 15:16:02 -04:00

67 lines
2.0 KiB
Python

# RiddleAPI
# ---------
# By Chris Proctor
# The Riddle API takes care of connecting to the server.
import requests
import random
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, params=params)
if response.ok:
return(response.json())
else:
raise APIError(response.json()['errors'])
def get_random_riddle(self):
"Fetches all riddles from the server and then randomly returns one"
route = "/random"
riddle_list = self.get_all_riddles()
return random.choice(riddle_list)
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'])