im trying to write this code where I request this information from openweathermap.org thourgh an api and try to print the temperature and location at the current time.
Most of the code is kind off a mix of the tips I could find on the internet.
Now I get this error and im stuck. Can anyone help me on the right path again?
Heres my code:
import urllib.request, urllib.parse, urllib.error
import json
while True:
zipcode = input('Enter zipcode: ')
if len(zipcode) < 1: break
url = 'http://api.openweathermap.org/data/2.5/weather?
zip='+zipcode+',nl&appid=db071ece9a338a36e9d7a660ec4f0e37?'
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
try:
js = json.loads(data)
except:
js = None
temp = js["main"]["temp"]
loc = js["name"]
print("temperatuur:", temp)
print("locatie:", loc)
So the url is this: http://api.openweathermap.org/data/2.5/weather?zip=3032,nl&appid=db071ece9a338a36e9d7a660ec4f0e37
The error im getting is:
Enter zipcode: 3343 Retrieving http://api.openweathermap.org/data/2.5/weather?zip=3343,nl&appid=db071ece9a338a36e9d7a660ec4f0e37? Traceback (most recent call last): File "weatherapi2.py", line 12, in uh = urllib.request.urlopen(url) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open response = meth(req, response) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 401: Unauthorized
After some troubleshooting i found your issue. You have an extra '?' at the end of your url in your python.
Remove that and your request works fine. Tried it with this code and worked-
import urllib.request, urllib.parse, urllib.error
import json
while True:
zipcode = input('Enter zipcode: ')
if len(zipcode) < 1: break
url = 'http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+',nl&appid=db071ece9a338a36e9d7a660ec4f0e37'
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
try:
js = json.loads(data)
except:
js = None
temp = js["main"]["temp"]
loc = js["name"]
print("temperatuur:", temp)
print("locatie:", loc)