|

|  How to Fetch Weather Data Using WeatherAPI.com in Python

How to Fetch Weather Data Using WeatherAPI.com in Python

October 31, 2024

Learn how to easily fetch weather data in Python using WeatherAPI.com. This guide simplifies the process for seamless integration in your projects.

How to Fetch Weather Data Using WeatherAPI.com in Python

 

Install Required Packages

 

  • Before fetching weather data, ensure you have the required Python packages installed. Primarily, you'll need `requests` to make HTTP requests. If it's not already installed, you can add it to your environment.

 

pip install requests

 

Accessing the Weather API

 

  • The WeatherAPI provides current weather data via its API endpoints. To use the API, integrate the following Python code snippet into your script, replacing `YOUR_API_KEY` with your actual API key and `CITY_NAME` with the desired location.

 

import requests

api_key = "YOUR_API_KEY"
base_url = "http://api.weatherapi.com/v1"

def fetch_weather(city_name):
    # Build the complete url
    complete_url = f"{base_url}/current.json?key={api_key}&q={city_name}"

    # Make the HTTP request to the WeatherAPI
    response = requests.get(complete_url)

    # Return the JSON data if the response is successful
    if response.status_code == 200:
        return response.json()
    else:
        return None

 

Parse and Display the Weather Data

 

  • Once you've successfully fetched the weather data, you can parse it to extract meaningful information. The JSON response will include various data points like temperature, humidity, and weather conditions. Here's how to parse and display it.

 

def display_weather_info(weather_data):
    if weather_data:
        # Extract data
        location = weather_data["location"]["name"]
        region = weather_data["location"]["region"]
        country = weather_data["location"]["country"]
        temperature = weather_data["current"]["temp_c"]
        condition = weather_data["current"]["condition"]["text"]

        # Display data
        print(f"Weather in {location}, {region}, {country}:")
        print(f"Temperature: {temperature}°C")
        print(f"Condition: {condition}")
    else:
        print("Error retrieving weather data.")

 

Executing the Script

 

  • With the functions defined, you can now execute your script to fetch and display the weather information. Here is how you integrate everything and run the script.

 

def main():
    city_name = "London"  # Example city, change it as required
    weather_data = fetch_weather(city_name)
    display_weather_info(weather_data)

if __name__ == "__main__":
    main()

 

Handling Errors and Exceptions

 

  • While interacting with external APIs, it's crucial to handle potential errors gracefully. Consider using try-except blocks to catch exceptions during HTTP requests or JSON parsing.

 

def fetch_weather(city_name):
    try:
        complete_url = f"{base_url}/current.json?key={api_key}&q={city_name}"
        response = requests.get(complete_url)
        response.raise_for_status()  # Raises HTTPError for bad responses
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
        return None

 

Conclusion

 

  • This example demonstrates how to use WeatherAPI.com to fetch and display weather data in Python. It covers URL construction, handling responses, parsing JSON, and displaying results effectively.