Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Fetch Weather Data from a Public API in Python

Fetches and parses weather data from a free public API using only the Python standard library.

Easy Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Python code

14 lines
Python 3.9+
import urllib.request
import json

def get_weather(city):
    base_url = f"https://wttr.in/{city}?format=j1"
    with urllib.request.urlopen(base_url) as response:
        data = json.loads(response.read().decode())
    current = data["current_condition"][0]
    temp = current["temp_C"]
    desc = current["weatherDesc"][0]["value"]
    return f"Weather in {city}: {temp}°C, {desc}"

if __name__ == "__main__":
    print(get_weather("London"))

Output

stdout
Weather in London: 15°C, Partly cloudy

How it works

This code uses urllib.request.urlopen to make an HTTP GET request to the wttr.in API, which returns JSON when the ?format=j1 query parameter is provided. The response is decoded and parsed with json.loads, then specific fields are accessed from the current_condition list. The function returns a formatted string. The if __name__ == "__main__" guard ensures the code only runs when executed directly.

Common mistakes

  • Forgetting to decode bytes before parsing JSON.
  • Assuming the API response always contains the expected keys without error handling.
  • Hardcoding the city name instead of accepting user input.

Variations

  1. Use `requests.get` from the third-party `requests` library for a more concise HTTP request.
  2. Accept city as command-line argument via `sys.argv`.

Real-world use cases

  • Building a simple CLI weather app for quick updates when planning outdoor work.
  • Integrating live weather conditions into a dashboard or monitoring system.
  • Automating weather-based alerts for agriculture or event logistics.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.