Skip to content

Instantly share code, notes, and snippets.

@Ostapp
Created February 14, 2016 20:23
Show Gist options
  • Save Ostapp/35ad582a4afbfbec40f8 to your computer and use it in GitHub Desktop.
Save Ostapp/35ad582a4afbfbec40f8 to your computer and use it in GitHub Desktop.

Weather forecast

  1. Read the developer documentation of Forecast.io's API: https://developer.forecast.io/
  2. Register to get your developer key
  3. Use the Requests library and JSON to get a weekly forecast in degree Celsius (°C)
  4. Print the min and max temperature and the amount of rain forecasted for the next 7 days
import requests
import json
# string formatting reminder
s = 'valami {a}, something {b}'
s.format(a=1, b=5)
# 'valami 1, something 5'
# Budapest
longitude = 19.05
latitude = 47.53
url_template = 'https://api.forecast.io/forecast/{api}/{lat},{lon}'
apikey = '.........'
url = url_template.format(api=apikey, lat=latitude, lon=longitude)
# stock
r = requests.get(url)
# r.text -> json.loads()
if r.ok:
data = json.loads(r.text)
# r.json()
if r.ok:
data2 = r.json()
# data == data2 -> True
# query parameters
# url
r = requests.get(url + '?units=si')
if r.ok:
data_si = r.json()
# requrests params dict
params_dict = {
'units': 'si',
'lang': 'es'
}
r = requests.get(url, params=params_dict)
if r.ok:
data_si_es = r.json()
# HTTP
# 1. URL (endpoint)
# 2. method name: GET, POST, (PUT, DELETE, etc.)
# 3. query parameter:
# after url
# single: ?units=si
# multiple: ?units=si&lang=es, order not important: ?lang=es&units=si
# 4. response data and return code (200, 404)
# URL
# 1. if GET: Browser, possibly JSONView, https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment