Skip to content

Instantly share code, notes, and snippets.

@sagunsh
Created January 19, 2020 11:12
Show Gist options
  • Save sagunsh/39cb4cfa54fd4f262938a6180a940a49 to your computer and use it in GitHub Desktop.
Save sagunsh/39cb4cfa54fd4f262938a6180a940a49 to your computer and use it in GitHub Desktop.
Search route
@app.route('/city')
def search_city():
API_KEY = 'your api key' # initialize your key here
city = request.args.get('q') # city name passed as argument
# call API and convert response into Python dictionary
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={API_KEY}'
response = requests.get(url).json()
# error like unknown city name, inavalid api key
if response.get('cod') != 200:
message = response.get('message', '')
return f'Error getting temperature for {city.title()}. Error message = {message}'
# get current temperature and convert it into Celsius
current_temperature = response.get('main', {}).get('temp')
if current_temperature:
current_temperature_celsius = round(current_temperature - 273.15, 2)
return f'Current temperature of {city.title()} is {current_temperature_celsius} ℃'
else:
return f'Error getting temperature for {city.title()}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment