Files
lab_riddles/api.py
ambreenn 62cd82b9f9 I changed the get riddle, get random riddle, and the add riddles functions. I had to add in the parameters to get the response needed. At first I forgot to add the params variable to the get random riddle function so it was not working but then later realized the issue. I added error codes that seemeed reasonable
1. One service I use regularly is spotify to listen to music. One feature is creating playlists with different amount of songs in them. One thing behind the scenes with HTTP requests could be with trying to add a song that already exists in a playlist, this would result in some message saying the song is already in the playlist. If the song is not in the playlist it gets added.
2. I will definitly say that I was thinking too much about the lab and ended up trying complicated things but in reality it was a simple fix. This makes me think more about my tech interactions as simpler than I would have expected. However with the errors I recieved it shows how much more there is behind that I didn't see. I was able to see what actually goes into coding an application.
2026-02-18 11:34:19 -05:00

67 lines
2.0 KiB
Python
Executable File

# 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('errors')
def get_random_riddle(self):
"Fetches all riddles from the server and then randomly returns one"
riddles = self.get_all_riddles()
if len(riddles) != 0:
return choice(riddles)
else:
return APIError('no riddles available')
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'])