Example output
**Objective:** Create a well-structured and concise Python code that fetches weather information for a given city using an API.
**Utilize Module/Library:** `requests` for making HTTP requests and `json` for handling JSON responses.
**Optimization:** The code is optimized for efficiency by handling potential errors gracefully and using appropriate HTTP status codes for validation.
**Coding Standards/Good Practices:** Follow PEP 8 coding standards and include meaningful variable/function names and comments for clarity.
**Test Cases/Scenarios:** Test the code with a valid city, an invalid city, and handle potential edge cases like a network failure or an unreachable API.
```python
import requests
import json
def get_weather(city_name):
"""
Fetches weather information for a given city using an API.
Args:
- city_name (str): Name of the city.
Returns:
- dict: Weather information in a dictionary format.
Raises:
- requests.exceptions.RequestException: If there is an issue with the HTTP request.
- ValueError: If the city name is not provided or the API response is not in JSON format.
"""
# Check if the city name is provided
if not city_name:
raise ValueError("City name is required.")
# API endpoint for weather information
api_url = f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid=YOUR_API_KEY"
try:
# Make the HTTP request
response = requests.get(api_url)
# Check if the request was successful (HTTP status code 200)
response.raise_for_status()
# Parse the JSON response
weather_data = response.json()
# Check if the response contains weather information
if "main" in weather_data and "weather" in weather_data:
return weather_data
else:
raise ValueError("Invalid response format. Missing weather information.")
except requests.exceptions.RequestException as req_err:
raise req_err
except json.JSONDecodeError:
raise ValueError("Invalid JSON format in the API response.")
if __name__ == "__main__":
# Test cases
try:
# Valid city
city_weather = get_weather("London")
print("Weather in London:", city_weather)
# Invalid city
invalid_city_weather = get_weather("InvalidCityName")
print("Weather in InvalidCityName:", invalid_city_weather)
except requests.exceptions.RequestException as req_err:
print(f"Error making HTTP request: {req_err}")
except ValueError as value_err:
print(f"ValueError: {value_err}")
```
**Comments:**
- Replace `"YOUR_API_KEY"` in the `api_url` variable with a valid OpenWeatherMap API key.
- The `get_weather` function returns a dictionary containing weather information or raises appropriate exceptions.
- Test cases demonstrate how to use the `get_weather` function for both valid and invalid city names.
- Handle exceptions to provide meaningful error messages.
- Ensure to keep sensitive information (like API keys) secure and do not share them in public repositories.