0
0
PythonProgramBeginner · 2 min read

Python Program to Get Weather Data Using API

Use Python's 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

InputCity: London
OutputTemperature: 15°C, Weather: Clear sky
InputCity: New York
OutputTemperature: 22°C, Weather: Few clouds
InputCity: InvalidCity
OutputError: City not found
🧠

How to Think About It

To get weather data, first decide which city you want info for. Then send a request to a weather API with that city name. The API sends back data in JSON format. You read this data and pick out the temperature and weather description to show to the user.
📐

Algorithm

1
Get the city name as input
2
Build the API request URL with the city and your API key
3
Send a GET request to the API
4
Check if the response is successful
5
Parse the JSON response to extract temperature and weather description
6
Print or return the weather information
💻

Code

python
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")
Output
Temperature: 15°C, Weather: clear sky
🔍

Dry Run

Let's trace the example with city 'London' through the code

1

Set city and API key

city = 'London', api_key = 'your_api_key_here'

2

Build URL

url = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key_here&units=metric'

3

Send GET request

response.status_code = 200 (success)

4

Parse JSON

data = {'main': {'temp': 15}, 'weather': [{'description': 'clear sky'}]}

5

Extract and print

temp = 15, weather = 'clear sky', output = 'Temperature: 15°C, Weather: clear sky'

StepActionValue
1Set cityLondon
2Build URLhttp://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key_here&units=metric
3Response status200
4Parse JSON temp15
5Parse JSON weatherclear 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

Using the 'http.client' library
python
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']}")
This method uses built-in libraries but is more complex and less readable than requests.
Using 'urllib' library
python
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']}")
This uses built-in urllib but requires more code to handle errors and is less straightforward.

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.

ApproachTimeSpaceBest For
requests libraryO(1)O(1)Simple and readable code
http.client libraryO(1)O(1)No extra packages, more control
urllib libraryO(1)O(1)Built-in but more verbose
💡
Always keep your API key secret and do not share it publicly.
⚠️
Beginners often forget to add the correct units parameter, causing temperature to show in Kelvin instead of Celsius.