Python Program that interacts with a Web APIs
To fetch weather data using the OpenWeatherMap API. This example demonstrates how to send requests, handle responses, and process JSON data.
Weather Data Fetcher: Interacting with Web APIs
import requests
# Function to fetch weather data
def fetch_weather(city, api_key):
# API endpoint
base_url = "https://api.openweathermap.org/data/2.5/weather"
# Parameters for the API request
params = {
'q': city,
'appid': api_key,
'units': 'metric' # Get temperature in Celsius
}
try:
# Make the GET request to the API
response = requests.get(base_url, params=params)
response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx)
# Parse the JSON response
weather_data = response.json()
# Extract and display relevant information
city_name = weather_data['name']
temperature = weather_data['main']['temp']
weather_condition = weather_data['weather'][0]['description']
humidity = weather_data['main']['humidity']
wind_speed = weather_data['wind']['speed']
print(f"\nWeather in {city_name}:")
print(f"Temperature: {temperature}°C")
print(f"Condition: {weather_condition.capitalize()}")
print(f"Humidity: {humidity}%")
print(f"Wind Speed: {wind_speed} m/s")
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
except KeyError:
print("Error: Unable to retrieve weather information. Check the city name or API key.")
# Main Program
if __name__ == "__main__":
# Replace with your OpenWeatherMap API key
api_key = "your_openweathermap_api_key"
# Input city name from the user
city = input("Enter the city name: ")
# Fetch and display weather information
fetch_weather(city, api_key)
Program Highlights
1. API Interaction:
- Sends a GET request to the OpenWeatherMap API with parameters like city name and API key.
- Handles errors such as invalid city names or connectivity issues.
2. JSON Parsing:
- Extracts relevant weather information like temperature, condition, humidity, and wind speed.
3. User Input:
- Takes a city name as input from the user to fetch weather data for that location.
How to Use the Program
1. Sign Up for OpenWeatherMap:
- Visit [OpenWeatherMap](https://openweathermap.org/).
- Create an account and generate an API key.
2. Replace the `api_key` Variable:
- Replace `"your_openweathermap_api_key"` with your actual API key.
3. Run the Program:
- Enter the name of a city when prompted.
- The program will display the current weather information.
Sample Output
Enter the city name: London
Weather in London:
Temperature: 15°C
Condition: Clear sky
Humidity: 65%
Wind Speed: 3.5 m/s
Features Covered
Request Handling:
- Uses `requests` to send HTTP requests and handle responses.
Error Handling:
- Handles connectivity issues and invalid inputs gracefully.
Dynamic Input:
- Fetches data for any city entered by the user.
This program can be extended to save data, handle multiple cities, or integrate additional features like forecasting or graphical visualization.
Comments
Post a Comment