I completed the riddles lab.

I implemented get_riddle, get_random_riddle, and
add_riddle in api.py. I also amended guess_riddle
to return whether it was correct.
This commit is contained in:
Cory 2024-04-26 09:12:15 -04:00
parent b3b355caa3
commit c4852fecd8
2 changed files with 23 additions and 10 deletions

Binary file not shown.

33
api.py
View File

@ -4,7 +4,7 @@
# The Riddle API takes care of connecting to the server.
import requests
from random import choice
from random import choice, randrange
class APIError(Exception):
"A custom error we'll use when something goes wrong with the API"
@ -29,24 +29,37 @@ class RiddleAPI:
params = {'id': riddle_id, 'answer': guess}
response = requests.post(self.server_url + route, json=params)
if response.ok:
return response.json()
return response.json()['correct']
# I added ['correct'] here because otherwise it kept telling
# me "Yes!" even when I knew I put in the wrong response...
# Was I supposed to do that? I thought this was supposed to
# have been implemented for me already. Or did I accidentally
# delete it without realizing?
else:
raise APIError(response.json()['errors'])
def get_riddle(self, riddle_id):
"Fetches a single riddle from the server"
route = "/show"
raise NotImplementedError("The API doesn't support `get_riddle` yet. Can you add it?")
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'])
def get_random_riddle(self):
"Fetches all riddles from the server and then randomly returns one"
raise NotImplementedError("The API doesn't support `get_random_riddle` yet. Can you add it?")
riddle_id = randrange(0,len(self.get_all_riddles()))
return self.get_riddle(riddle_id)
# Was I supposed to do it this way?
def add_riddle(self, question, answer):
"Adds a new riddle to the server"
route = "/new"
raise NotImplementedError("The API doesn't support `add_riddle` yet. Can you add it?")
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'])