Python project 03
Python Weather App Using API
Create a command-line weather app that looks up a city, requests live weather data, and presents the result in a friendly format. This project is a practical introduction to APIs, JSON data, URL parameters, and handling network errors without making the user feel lost.
Build API skills in the Python courseView all project ideas
What you will build
The user enters a city name. The program first asks Open-Meteo’s geocoding service for that city’s latitude and longitude, then requests the current weather for those coordinates. No API key or third-party package is required for this learning version.
Skills practised
- Working with public APIs
- JSON data and dictionaries
- URL query parameters
- Network error handling
Requirements
- Python 3.8 or later
- An internet connection
- No package installation
- About 30 minutes to build
Full Python code
Save the file as weather_app_using_api.py. The code uses Python’s built-in urllib module, so you can focus on the API workflow before learning external HTTP libraries. Open-Meteo is used here because it provides public weather and geocoding endpoints for practice.
import json
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
WEATHER_DESCRIPTIONS = {
0: "Clear sky",
1: "Mainly clear",
2: "Partly cloudy",
3: "Overcast",
45: "Fog",
48: "Rime fog",
51: "Light drizzle",
53: "Moderate drizzle",
55: "Heavy drizzle",
61: "Light rain",
63: "Moderate rain",
65: "Heavy rain",
71: "Light snow",
73: "Moderate snow",
75: "Heavy snow",
80: "Rain showers",
81: "Moderate rain showers",
82: "Violent rain showers",
95: "Thunderstorm",
}
def get_json(url):
"""Request JSON data from a public API."""
request = Request(url, headers={"User-Agent": "PythonWeatherPractice/1.0"})
with urlopen(request, timeout=15) as response:
return json.load(response)
def find_city(city_name):
query = urlencode({"name": city_name, "count": 1, "language": "en", "format": "json"})
data = get_json(f"https://geocoding-api.open-meteo.com/v1/search?{query}")
results = data.get("results", [])
return results[0] if results else None
def get_weather(latitude, longitude):
query = urlencode(
{
"latitude": latitude,
"longitude": longitude,
"current": "temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m",
"timezone": "auto",
}
)
return get_json(f"https://api.open-meteo.com/v1/forecast?{query}")["current"]
def show_weather(city):
current = get_weather(city["latitude"], city["longitude"])
description = WEATHER_DESCRIPTIONS.get(current["weather_code"], "Unknown conditions")
country = city.get("country", "")
print(f"\nWeather for {city['name']}, {country}")
print(f"Condition: {description}")
print(f"Temperature: {current['temperature_2m']} C")
print(f"Feels like: {current['apparent_temperature']} C")
print(f"Humidity: {current['relative_humidity_2m']}%")
print(f"Wind speed: {current['wind_speed_10m']} km/h\n")
def main():
print("Python Weather App")
print("Uses the public Open-Meteo API. Type q to quit.\n")
while True:
city_name = input("Enter a city: ").strip()
if city_name.lower() in {"q", "quit", "exit"}:
print("Weather app closed.")
break
if not city_name:
print("Please enter a city name.\n")
continue
try:
city = find_city(city_name)
if city is None:
print("City not found. Try a more specific name.\n")
continue
show_weather(city)
except (HTTPError, URLError, TimeoutError) as error:
print(f"Could not reach the weather service: {error}\n")
except (KeyError, json.JSONDecodeError) as error:
print(f"The weather service returned unexpected data: {error}\n")
if __name__ == "__main__":
main()
How the weather lookup works
find_city() sends the city name to the geocoding endpoint. A city name alone is not enough for a weather forecast because different places can share the same name; the response gives the program a latitude and longitude for the best result.
get_weather() passes those coordinates to the forecast endpoint and asks only for the current fields the app needs: temperature, humidity, apparent temperature, weather code, and wind speed. The response is JSON, which Python reads into ordinary dictionaries.
The weather API returns a numeric weather code rather than a complete sentence. The WEATHER_DESCRIPTIONS dictionary changes those codes into a readable label such as Clear sky or Moderate rain. The program also catches common network errors so a temporary service or connection problem does not crash the app.
Run the project
- Open a terminal in the folder containing the saved file.
- Run
python weather_app_using_api.py, orpy weather_app_using_api.pyon many Windows installations. - Enter a city such as
VisakhapatnamorHyderabad. - Type
qwhen you want to close the app.
Python Weather App
Uses the public Open-Meteo API. Type q to quit.
Enter a city: Visakhapatnam
Weather for Visakhapatnam, India
Condition: Partly cloudy
Temperature: 28.1 C
Feels like: 33.1 C
Notes for your notebook
- API: an API lets one program request data or a service from another system.
- JSON: JSON data usually becomes Python dictionaries and lists after it is decoded.
- Timeout: network requests should have a timeout so the program does not wait forever.
- External services: public API availability and response formats can change, so production apps should follow the provider’s current documentation and usage policy.
Ways to extend this project
Add a five-day forecast, unit selection, saved favourite cities, or icons in a Tkinter interface. You could also show the data in a small Flask application after comparing Django, Flask, and FastAPI. These changes turn a useful console project into a more complete portfolio item.
Where to take your weather app next
To turn this API exercise into a web project, compare Django, Flask, and FastAPI and choose a framework that suits the interface you want to build. Before adding packages, learn how virtual environments and pip keep a project clean. For a broader view of deploying a front end, back end, and API, read this Python full-stack project architecture guide. For instructor-led practice, visit the Python programming course in Vizag.