Python Program to Get Weather Data Using API
requests library to call a weather API like OpenWeatherMap with requests.get(), then parse the JSON response with response.json() to get weather data.Examples
How to Think About It
Algorithm
Code
import requests api_key = "your_api_key_here" city = "London" url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" response = requests.get(url) if response.status_code == 200: data = response.json() temp = data["main"]["temp"] weather = data["weather"][0]["description"] print(f"Temperature: {temp}°C, Weather: {weather}") else: print("Error: City not found or API request failed")
Dry Run
Let's trace the example with city 'London' through the code
Set city and API key
city = 'London', api_key = 'your_api_key_here'
Build URL
url = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key_here&units=metric'
Send GET request
response.status_code = 200 (success)
Parse JSON
data = {'main': {'temp': 15}, 'weather': [{'description': 'clear sky'}]}
Extract and print
temp = 15, weather = 'clear sky', output = 'Temperature: 15°C, Weather: clear sky'
| Step | Action | Value |
|---|---|---|
| 1 | Set city | London |
| 2 | Build URL | http://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key_here&units=metric |
| 3 | Response status | 200 |
| 4 | Parse JSON temp | 15 |
| 5 | Parse JSON weather | clear sky |
Why This Works
Step 1: Send API request
The code uses requests.get() to ask the weather API for data about the city.
Step 2: Check response
It checks if the response status is 200, meaning the request worked and data is available.
Step 3: Extract data
The JSON response is parsed to get temperature from main.temp and weather description from weather[0].description.
Step 4: Show result
Finally, it prints the temperature and weather in a friendly format.
Alternative Approaches
import http.client, json conn = http.client.HTTPSConnection('api.openweathermap.org') conn.request('GET', '/data/2.5/weather?q=London&appid=your_api_key_here&units=metric') res = conn.getresponse() data = res.read() weather_data = json.loads(data) print(f"Temperature: {weather_data['main']['temp']}°C, Weather: {weather_data['weather'][0]['description']}")
import urllib.request, json url = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key_here&units=metric' with urllib.request.urlopen(url) as response: data = json.loads(response.read()) print(f"Temperature: {data['main']['temp']}°C, Weather: {data['weather'][0]['description']}")
Complexity: O(1) time, O(1) space
Time Complexity
The program makes a single API call and processes a small JSON response, so time is constant regardless of input size.
Space Complexity
Only a small amount of memory is used to store the JSON response and extracted data, so space is constant.
Which Approach is Fastest?
Using the requests library is fastest and easiest for beginners due to its simplicity and built-in JSON parsing.
| Approach | Time | Space | Best For |
|---|---|---|---|
| requests library | O(1) | O(1) | Simple and readable code |
| http.client library | O(1) | O(1) | No extra packages, more control |
| urllib library | O(1) | O(1) | Built-in but more verbose |