I'm programming in school and will soon need to program my final piece. The following program (written in python's programming language) as a program I'm writing simply to practice accessing APIs. I'm attempting to access the API for a sight based on a game. The idea on the program is to check this API every 30 seconds to check for changes in the data, by storing to sets of data ('baseRank' and 'basePP') as soon as it's running, then comparing this data with new data taken 30 seconds later. Here is my program:
import time
apiKey = '###'
rankDifferences = []
ppDifferences = []
const = True
username = '- Legacy'
url = "https://osu.ppy.sh/api/get_user?u={1}&k={0}".format(apiKey,username)
import urllib.request, json
with urllib.request.urlopen(url) as url:
stats = json.loads(url.read().decode())
stats = stats[0]
basePP = stats['pp_raw']
print(basePP)
baseRank = stats['pp_rank']
print(baseRank)
while const == True:
time.sleep(30)
import urllib.request, json
with urllib.request.urlopen(url) as url:
check = json.loads(url.read().decode())
check = check[0]
rankDifference = baseRank + check['pp_rank']
ppDifference = basePP + check['pp_raw']
baseRank = check['pp_raw']
basePP = check['pp_raw']
if rankDifference != 0:
print(rankDifference)
if ppDifference != 0:
print(ppDifference)`
Please note, where I have written 'apiKey = '###'', I am in fact using a real, working API key, but I've hidden it as the site asks you not to share your api key with others. Here is the state of the shell after running:
5206.55
12045
Traceback (most recent call last):
File "C:/Users/ethan/Documents/osu API Accessor.py", line 23, in with urllib.request.urlopen(url) as url: File
"C:\Users\ethan\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", >line 223, in urlopen return opener.open(url, data, timeout)
File
"C:\Users\ethan\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", >line 518, in open protocol = req.type
AttributeError: 'HTTPResponse' object has no attribute 'type'
As you can see, it does print both 'basePP' and 'baseRank', proving that I can access this API. The problem seems to be when I try to access it a second time. To be completely honest, I'm not entirely sure what this error means.. So if you wouldn't mind taking the time to explain and/or help fix this error, it would be greatly appreciated.
Side note: This is my first time using this forum so if I'm doing anything wrong, I'm very sorry!
The problem seems to be when you do:
with urllib.request.urlopen(url) as url:
stats = json.loads(url.read().decode())
Your use of the url
variable is changing it, so that when you try and use it later it doesn't work.
Try something like:
with urllib.request.urlopen(url) as page:
stats = json.loads(page.read().decode())
and it should be okay.