Urllib.urequest, APi use and JSON decoding of OpenWeatherMap

We have temperature from the sensor, but it would be good to know what the weather is like now from an Application Programming Interface (API).
Head over to the website: http://www.openweathermap.org to see for yourself what is information possible to achieve with micropython or any python code.

This is a fun bit of code to help you explore for yourself.

import urequests
import ujson
import utime

#time in unix time

def time_converter(time):
(year, month, mday, hour, minute, second, weekday, yearday) = utime.localtime(time)
return hour,minute,second

addr = ‘http://sample.openweathermap.org/data/2.5/weather?q=London,uk&appid=
appid=‘b6907d289e10d714a6e88b30761fae22’
url = addr+appid
data_url = urequests.get(url)
utime.sleep(5)
data_line = data_url.text
data_url.close()
utime.sleep(5)
raw_api_dict = ujson.loads(data_line)

data = dict(city=raw_api_dict.get(‘name’),
country=raw_api_dict.get(‘sys’).get(‘country’),
temp=raw_api_dict.get(‘main’).get(‘temp’)- 273.15,
temp_max=raw_api_dict.get(‘main’).get(‘temp_max’)- 273.15,
temp_min=raw_api_dict.get(‘main’).get(‘temp_min’) - 273.15,
humidity=raw_api_dict.get(‘main’).get(‘humidity’),
pressure=raw_api_dict.get(‘main’).get(‘pressure’),
sky=raw_api_dict[‘weather’][0][‘main’],
sunrise=raw_api_dict.get(‘sys’).get(‘sunrise’),
sunset=raw_api_dict.get(‘sys’).get(‘sunset’),
wind=raw_api_dict.get(‘wind’).get(‘speed’),
wind_deg=raw_api_dict.get(‘deg’),
dt=raw_api_dict.get(‘dt’),
cloudiness=raw_api_dict.get(‘clouds’).get(‘all’)
)

m_symbol = ‘\xb0’ + ‘C’
print(’---------------------------------------’)
print(‘Current weather in: {}, {}:’.format(data[‘city’], data[‘country’]))
print(data[‘temp’], m_symbol, data[‘sky’])
print(‘Max: {}, Min: {}’.format(data[‘temp_max’], data[‘temp_min’]))
print(’’)
print(‘Wind Speed: {}, Degree: {}’.format(data[‘wind’], data[‘wind_deg’]))
print(‘Humidity: {}’.format(data[‘humidity’]))
print(‘Cloud: {}’.format(data[‘cloudiness’]))
print(‘Pressure: {}’.format(data[‘pressure’]))
(hour,minute,second) = time_converter(data[‘sunrise’])
print(‘Sunrise at: {0:02}:{1:02}:{2:02}’.format(hour,minute,second))
(hour,minute,second) = time_converter(data[‘sunset’])
print(‘Sunset at: {0:02}:{1:02}:{2:02}’.format(hour,minute,second))
print(’’)
(hour,minute,second) = time_converter(data[‘dt’])
print(‘Last update from the server: {0:02}:{1:02}:{2:02}’.format(hour,minute,second))
print(’---------------------------------------’)

1 Like

Cool! Thanks for the code!