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.
Python code
14 linesimport 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
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
- Use `requests.get` from the third-party `requests` library for a more concise HTTP request.
- 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
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert CSV Files to JSON in Python easy
- Convert Image to ASCII Art in Python medium
Keep learning
Related tutorials and quizzes for this topic.