[Python] KeyError: 'main' in OpenWeatherMap API Response with Tkinter GUI – How to Safely...

Discussão em 'Python' iniciado por Stack, Agosto 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm building a simple weather application using Python's Tkinter for the GUI and the OpenWeatherMap API to fetch weather data. The application includes a search bar for entering a city name and a submit button to fetch the weather information. However, when I try to access the 'main' key in the JSON response, I encounter a KeyError: main.

    import tkinter as tk
    import requests
    from tkinter import messagebox

    def get_weather():
    city_name = city_entry.get()
    api_key = 'your_api_key_here'
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={api_key}"

    try:
    response = requests.get(url)
    data = response.json()
    print(data) # Debugging line to inspect the response

    # Attempting to access 'main' key
    temperature = data['main']['temp']
    humidity = data['main']['humidity']
    print(f"Temperature: {temperature}°C, Humidity: {humidity}%")

    except KeyError as e:
    messagebox.showerror("Data Error", f"Missing key in response: {e}")
    except requests.exceptions.RequestException as e:
    messagebox.showerror("Request Error", f"An error occurred: {e}")

    # Tkinter GUI setup
    root = tk.Tk()
    root.title("Weather App")

    city_entry = tk.Entry(root)
    city_entry.pack()

    submit_button = tk.Button(root, text="Get Weather", command=get_weather)
    submit_button.pack()

    root.mainloop()


    Issue: When I enter a city name and click the submit button, I receive the following error:

    KeyError: 'main'


    Upon inspecting the data dictionary, I noticed that sometimes the 'main' key is missing. This seems to occur when the city name is misspelled or does not exist.

    Questions: What is the best way to handle missing keys in the JSON response from the OpenWeatherMap API?

    How can I validate the city name before making the API request to ensure the 'main' key is present in the response?

    Are there any improvements I can make to my error handling to provide a better user experience in case of invalid city names or API issues?

    Additional Information:

    • I have verified that the API key is correct and active.
    • The application works as expected when valid city names are entered.
    • I am using Python 3.8 and Tkinter 8.6.

    Any guidance or suggestions would be greatly appreciated!

    Continue reading...

Compartilhe esta Página