|

|  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.

 

Pre-order Friend AI Necklace

Pre-Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI Necklace

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

 

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

San Francisco

team@basedhardware.com
Title

Company

About

Careers

Invest
Title

Products

Omi Dev Kit 2

Openglass

Other

App marketplace

Affiliate

Privacy

Customizations

Discord

Docs

Help