· 4 years ago · May 03, 2021, 06:22 AM
1# Simple Weather report in python by ElectronicSheep 2021.
2
3#NOTE: you need to enter your API and City name in the variables below or this won't work!
4
5#You will need pytemperature to convert the temp from kelvin to Fahrenheit
6import requests, json, pytemperature
7
8base_url = "https://api.openweathermap.org/data/2.5/weather?"
9# You can put the name of the city you want in the next variable.
10city = "Put the city name you want here."
11#use your API key from openweathermap.org in the next variable or it won't work.
12API_KEY = "YOUR KEY HERE"
13URL = base_url + "q=" + city + "&appid=" + API_KEY
14response = requests.get(URL)
15if response.status_code == 200:
16 data = response.json()
17 main = data['main']
18 #use next line instead of the one I used if you are ok with Kelvin which is the default from the API.
19 #temperature = main['temp']
20 temperature = pytemperature.k2f(main['temp'])
21 humidity = main['humidity']
22 report = data['weather']
23 print(f"{city:-^30}")
24 print(f"Temperature: {temperature}")
25 print(f"Humidity: {humidity}")
26 print(f"Weather Report: {report[0]['description']}")
27else:
28 print("Error in the HTTP request")