Beginner Project: Build a Weather App with Python (Using APIs)

3D isometric smartphone showing a weather forecast connected to a cloud server API for a Python project.

Real-world applications don’t just use data you type in; they fetch data from the internet. A Python Weather App, for instance, would do this using APIs (Application Programming Interfaces).

In this project, we’ll build a tool that asks for a city name and tells you the current temperature. We’ll use the free OpenWeatherMap API, which is perfect for developing a weather app using Python.

Step 1: Get Your API Key

An API Key is like a password that lets you use a service crucial for accessing Python-based weather applications like yours.

  1. Go to OpenWeatherMap.org and sign up for a free account.
  2. Go to your API Keys tab and copy your unique key.

Step 2: Install the requests Library

Python has a built-in way to make web requests, but it’s messy. The requests library is the industry standard because it’s so easy to use, especially for weather-related applications.

pip install requests

Step 3: Fetching the Data

We need to construct a URL with your API key and the city name, then send it to OpenWeatherMap. This is an essential step for your Python Weather App.

import requests

API_KEY = "YOUR_API_KEY_HERE"  # Paste your key here!
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"

city = input("Enter a city name: ")

# Build the full URL with parameters
request_url = f"{BASE_URL}?appid={API_KEY}&q={city}"

# Send the GET request
response = requests.get(request_url)

# Check if it worked (Status Code 200 means OK)
if response.status_code == 200:
    data = response.json()
    print("Data fetched successfully!")
else:
    print("An error occurred.")

Step 4: Parsing the JSON

The data comes back in JSON format, which Python handles easily as a Dictionary. Proper parsing will ensure your Weather App functions smoothly with Python.

# ... (continuing from above if status_code == 200) ...
    data = response.json()
    
    # The temperature is buried deep in the dictionary!
    # It's usually in Kelvin, so let's convert it to Celsius.
    temp_kelvin = data["main"]["temp"]
    temp_celsius = temp_kelvin - 273.15
    
    weather_desc = data["weather"][0]["description"]
    
    print(f"Weather in {city}: {weather_desc}")
    print(f"Temperature: {temp_celsius:.2f}°C")

Challenge: Can you add a conversion to Fahrenheit? (Formula: (K − 273.15) × 9/5 + 32)

Similar Posts

Leave a Reply