How to Build a Simple Weather App in Python with OpenWeatherMap API

Dinithi Nethmini
6 min readMar 26, 2024

--

Building a simple weather app using Python and OpenWeatherMap API is a great way to practice your coding skills while creating a useful tool for checking weather conditions in various locations.

Images generated by Sky-inspired Weather App Concept

Step 1: Sign up for OpenWeatherMap API

To get started, you will need to sign up for OpenWeatherMap API. This will allow you to access weather data that you can use in your Python script. Simply head over to https://home.openweathermap.org/users/sign_up and create a free account. Once you have created your account, navigate to your dashboard and generate an API key. You will need this key to access the weather data.

Step 2: Install the Requests module

The Requests module will be used to make HTTP requests to OpenWeatherMap API, so you will need to install it before proceeding. We will use the Requests module to make HTTP requests to OpenWeatherMap API. You can install the Requests module by running the following command in your terminal:

Step 3: Import the Requests module and API key

Now that we have installed the Requests module and generated our API key, we can start coding. Open a new Python file in your favorite code editor and import the Requests module:

Next, create a variable to store your API key:

Replace YOUR_API_KEY with your actual API key.

Step 4: Build the weather app

Now that we have imported the Requests module and stored our API key, we can start building our weather app. The app will prompt the user for a city name and use the Requests module to access weather data for that city.

from tkinter import *
import requests
import json
from datetime import datetime

#Initialize Window

root =Tk()
root.geometry("400x400") #size of the window by default
root.resizable(0,0) #to make the window size fixed
#title of our window
root.title("Weather App")

# ----------------------Functions to fetch and display weather info
city_value = StringVar()


def time_format_for_location(utc_with_tz):
local_time = datetime.utcfromtimestamp(utc_with_tz)
return local_time.time()


city_value = StringVar()

def showWeather():
#Enter you api key, copies from the OpenWeatherMap dashboard
api_key = "28c19bd01dbbc1f4dcc5bdf0f9dff164" #sample API

# Get city name from user from the input field (later in the code)
city_name=city_value.get()

# API url
weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key

# Get the response from fetched url
response = requests.get(weather_url)

# changing response from json to python readable
weather_info = response.json()
tfield.delete("1.0", "end") #to clear the text field for every new output

#as per API documentation, if the cod is 200, it means that weather data was successfully fetched


if weather_info['cod'] == 200:
kelvin = 273 # value of kelvin

#-----------Storing the fetched values of weather of a city

temp = int(weather_info['main']['temp'] - kelvin) #converting default kelvin value to Celcius
feels_like_temp = int(weather_info['main']['feels_like'] - kelvin)
pressure = weather_info['main']['pressure']
humidity = weather_info['main']['humidity']
wind_speed = weather_info['wind']['speed'] * 3.6
sunrise = weather_info['sys']['sunrise']
sunset = weather_info['sys']['sunset']
timezone = weather_info['timezone']
cloudy = weather_info['clouds']['all']
description = weather_info['weather'][0]['description']

sunrise_time = time_format_for_location(sunrise + timezone)
sunset_time = time_format_for_location(sunset + timezone)

#assigning Values to our weather varaible, to display as output

weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}"
else:
weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!"



tfield.insert(INSERT, weather) #to insert or send value in our Text Field to display output


city_head = Label(root, text='Enter City Name', font='Arial 12 bold')
city_head.pack(pady=10)

inp_city = Entry(root, textvariable=city_value, width=24, font='Arial 14 bold')
inp_city.pack()

Button(root, command=showWeather, text="Check Weather", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5).pack(pady=20)

# To show output
weather_now = Label(root, text="The Weather is:", font='Arial 12 bold')
weather_now.pack(pady=10)

tfield = Text(root, width=46, height=10)
tfield.pack()

root.mainloop()

Your code effectively demonstrates how to build a simple weather app using Python and the OpenWeatherMap API. Let’s break down the code and summarize each part:

  1. User input: The script asks the user to enter a city name using the input() function. This city name will be used to fetch weather data from the API.
  2. URL construction: An API URL is constructed using the city name provided by the user and the API key from OpenWeatherMap. This URL is necessary for making the API request and retrieving weather data.
  3. API request: The script uses the requests library to send an HTTP GET request to the API URL. The response from the API is stored in the response variable.
  4. Response status check: The script checks the status code of the response to ensure that the request was successful. A status code of 200 indicates a successful request.
  5. Data extraction: If the request was successful, the script extracts the temperature and weather description from the JSON response using Python’s dictionary manipulation capabilities.
  6. Output: The extracted temperature and weather description are printed to the console.
  7. Error handling: If the request was not successful, an error message is printed to the console.

This simple weather app demonstrates the core functionality of fetching weather data for a given city using Python and the OpenWeatherMap API. You can further enhance this script by adding features such as handling multiple cities, displaying additional weather data, or creating a graphical user interface (GUI).

Step 5: Save and test the app

Save the Python file as “Weather App.py”. Now, with our weather app in place, we can test the application. Run the following command in the terminal

Enter a city name when prompted and hit Enter. The app should retrieve weather data for the given city and print the temperature and description to the console.

If you have just signed up to get your API key and get an error, grab a cup of coffee, it may take a little bit of time for it to be activated.

Retrieving weather forecast in Houston
Out Put In Weather App

Great job on completing your simple weather app! It’s an excellent starting point for building more complex applications using Python and APIs. Here are some suggestions on what to do next:

  • Customization: You can customize the look and feel of your weather app by using various Python libraries like colorama or termcolor to add colors and styles to your console output, or even integrate it with a GUI library like tkinter or PyQt.
  • Error handling: Enhance your error handling capabilities to ensure a smooth user experience even when something goes wrong. For example, you can include checks for invalid city names or handle network errors gracefully.
  • Save and load settings: Add functionality to save user preferences or settings, such as the last searched city or preferred temperature units, and load them on app startup for a personalized experience.
  • More features: Extend your app by integrating additional weather-related data like humidity, wind speed, or sunrise/sunset times. You can also include weather forecasts for multiple days, hourly forecasts, or even display weather maps and satellite imagery.
  • Testing: Write unit tests for your functions to ensure their correctness and catch any potential bugs early on.
  • Once you’re satisfied with your app, you can share it with others on platforms like GitHub or other code-sharing websites. This will allow you to showcase your skills, receive feedback, and collaborate with other developers.

Remember, there are numerous resources available online to help you improve your coding skills and build more advanced applications. Keep exploring and learning!

Thank you for reading! If you find my blogs interesting or would like to get in touch, reach out on here, Github or LinkedIn.

--

--

Dinithi Nethmini

Experienced software engineer with a passion for developing innovative programs that expedite the efficiency and effectiveness of organizational success.