Let’s create a project for building a simple weather app using Python and the OpenWeatherMap API to fetch current weather data.
1. Project Setup:
- Create a new Python project or script.
- Install necessary libraries:
pip install requests
2. OpenWeatherMap API Key:
- Obtain an API key from OpenWeatherMap by creating an account on their website.
3. Weather App:
- Use the OpenWeatherMap API to fetch current weather data:
import requests
def get_weather(api_key, city):
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
'q': city,
'appid': api_key,
'units': 'metric', # Use 'imperial' for Fahrenheit
}
# Send a GET request to the OpenWeatherMap API
response = requests.get(base_url, params=params)
# Check if the request was successful
if response.status_code == 200:
weather_data = response.json()
# Extract relevant information
temperature = weather_data['main']['temp']
description = weather_data['weather'][0]['description']
return f"The current weather in {city} is {temperature}°C with {description}."
else:
print(f"Failed to retrieve weather data. Status code: {response.status_code}")
return None
# Example usage
api_key = 'your_openweathermap_api_key'
city = input("Enter a city name: ")
weather_result = get_weather(api_key, city)
if weather_result:
print(weather_result)
4. User Interaction:
- Allow the user to input a city name and fetch the current weather:
def get_weather_and_display(api_key, user_city):
weather_result = get_weather(api_key, user_city)
if weather_result:
print(weather_result)
# User interaction loop
while True:
user_city = input("\nEnter a city name for weather information (or 'exit' to end):\n")
# Exit the loop if the user types 'exit'
if user_city.lower() == 'exit':
break
get_weather_and_display(api_key, user_city)
5. Project Conclusion:
- Summarize the project’s goals, outcomes, and potential improvements.
- Include any insights gained from building a simple weather app using the OpenWeatherMap API.
This project provides a basic example of using the OpenWeatherMap API to fetch current weather data for a specified city. You can expand the project by adding more features such as extended weather forecasts, graphical representations, or integrating with additional APIs for more comprehensive weather information.