Files
lab_riddles/api.py
erbrown2 bd266cc4dc I added code into api.py so client.py works now!!! super cool and fun!
1. Tik Tok is one service I use on my phone. A feature is new posts load automatically when I keep scrolling. Tik tok makes a GET request to Tik Tok users asking for the next set of posts. the requests includes headers with different parameterss then the server responds with 200 OK and sends back a JSON containing data. When I post, the app sends a POST request with the post ID and the servers responds confirming it was registered.
2. This lab was pretty fun! I think a bit differently on how apps and websites are created and used. I am more aware of how much data is being sent back and forth for a server to work successfully! In the end, it was really cool to be able to just enter a number for the riddle and guess the riddle.
2026-05-09 14:54:37 -04:00

69 lines
2.1 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"
response =requests.get(self.server_url + route, params = {"id": riddle_id})
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"
riddles = self.get_all_riddles()
if len(riddles) == 0:
raise APIError(["Sorry, there are no riddles on the server!"])
return choice(riddles)
def add_riddle(self, question, answer):
"Adds a new riddle to the server"
route = "/new"
response = request.post(
self.server_url + route,
json={"question": question, "answer": answer}
)
if response.ok:
return response.json()
else:
raise APIError(response.json()['errors'])