• Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Working With Webhooks in PHP

    Working With Webhooks in PHP

    My Backup Setup for Linux PCs

    My Backup Setup for Linux PCs

    Detecting Hidden WordPress Malware Disguised as Images

    Detecting Hidden WordPress Malware Disguised as Images

    Server-Side Image Conversion with Apache

    Server-Side Image Conversion with Apache

    Fastest Way to Extract a Massive .tar.gz File on Linux

    Fastest Way to Extract a Massive .tar.gz File on Linux

    Monitor SSL Expiration with Python

    Monitor SSL Expiration with Python

    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

  • Blog
    • All
    • Artificial Intelligence
    • Developer Life
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Imposter Syndrome as a Self-Taught Developer

    Imposter Syndrome as a Self-Taught Developer

    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attack Stats
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
  • Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Working With Webhooks in PHP

    Working With Webhooks in PHP

    My Backup Setup for Linux PCs

    My Backup Setup for Linux PCs

    Detecting Hidden WordPress Malware Disguised as Images

    Detecting Hidden WordPress Malware Disguised as Images

    Server-Side Image Conversion with Apache

    Server-Side Image Conversion with Apache

    Fastest Way to Extract a Massive .tar.gz File on Linux

    Fastest Way to Extract a Massive .tar.gz File on Linux

    Monitor SSL Expiration with Python

    Monitor SSL Expiration with Python

    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

  • Blog
    • All
    • Artificial Intelligence
    • Developer Life
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Imposter Syndrome as a Self-Taught Developer

    Imposter Syndrome as a Self-Taught Developer

    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attack Stats
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
Home Guides Programming Python

Retrieve Weather Data with Python

Jonathan Moore by Jonathan Moore
5 years ago
Reading Time: 2 mins read
A A
Retrieve Weather Data with Python
FacebookTwitter

This simple Python application works similarly to the one we created in Add NWS Weather to Your Website JavaScript guide. This is handy if we need to grab weather data as part of another Python application or if we wanted to use it as the base for a more powerful weather application.

Our Requirements

Before we get started, you will need to install the Requests HTTP library for Python. The Requests library allows us to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to URLs or to form-encode POST data.

pip install requests

Let’s Get Started

As with its JavaScript equivalent, we will be passing the latitude and longitude of the location that we want to retrieve the weather data from to the get_weather function. The data will then be extracted from the JSON data object and outputted to the terminal.

#!/usr/bin/python3

import requests
from requests.exceptions import HTTPError


def get_weather(lat, lng):
    # Build the `payload` for the requested data.
    payload = {
        'lat': lat,
        'lon': lng,
        'unit': 0,
        'lg': 'english',
        'FcstType': 'json'
    }

    # Set the `url` variable with the weather link.
    url = 'https://forecast.weather.gov/MapClick.php'

    try:
        # Send a GET request to retrieve the JSON data.
        response = requests.get(url, params=payload)

        # Check for HTTP errors before processing.
        response.raise_for_status()

        # Return the JSON object of the response.
        json = response.json()

        # Print out the values from the JSON data object.
        print("Location:",    json['location']['areaDescription'])
        print("Temperature:", json['currentobservation']['Temp'] + "°")
        print("Wind:",        json['currentobservation']['Winds'], "mph")
        print("Humidity:",    json['currentobservation']['Relh'] + "%")
        print("Dew Point:",   json['currentobservation']['Dewp'] + "°")
        print("Barometer:",   json['currentobservation']['SLP'], "in")
        print("Visibility:",  json['currentobservation']['Visibility'], "mi")
        print("Forecast:",    json['data']['text'][0])
    except HTTPError as http_err:
        print("HTTP Error Occurred:", http_err)
    except Exception as err:
        print("An Exception Occured:", err)


if __name__ == "__main__":
    # Call the 'get_weather' function and pass the latitude and logitude for
    # the location that we want to retrieve the weather information from.
    get_weather("38.349819", "-81.632622")

Terminal Output:

Location: Charleston WV<br>
Temperature: 69°<br>
Wind: 3 mph<br>
Humidity: 96%<br>
Dew Point: 68°<br>
Barometer: 30.13 in<br>
Visibility: 10.00 mi<br>
Forecast: Areas of fog after 4am.  Otherwise, mostly clear, with a low around 66. Calm wind.

Helpful Tip

There is a lot more weather information available within the JSON data object than is used for this basic project. You can output the entire JSON data object to your terminal or visit the NWS JSON file to see what data is available to use.

#!/usr/bin/python3

import requests
from requests.exceptions import HTTPError


def get_weather(lat, lng):
    # Build the `payload` for the requested data.
    payload = {
        'lat': lat,
        'lon': lng,
        'unit': 0,
        'lg': 'english',
        'FcstType': 'json'
    }

    # Set the `url` variable with the weather link.
    url = 'https://forecast.weather.gov/MapClick.php'

    try:
        # Send a GET request to retrieve the JSON data.
        response = requests.get(url, params=payload)

        # Check for HTTP errors before processing.
        response.raise_for_status()

        # Return the JSON object of the response.
        json = response.json()

        # Print all JSON data to terminal.
        print(json)
        
    except HTTPError as http_err:
        print("HTTP Error Occurred:", http_err)
    except Exception as err:
        print("An Exception Occured:", err)


if __name__ == "__main__":
    # Call the 'get_weather' function and pass the latitude and logitude for
    # the location that we want to retrieve the weather information from.
    get_weather("38.349819", "-81.632622")
Tags: JSONPythonRequestsWeather
ShareTweetSharePinShareShareScan
ADVERTISEMENT
Jonathan Moore

Jonathan Moore

I am a Software Architect and Senior Software Engineer with 30+ years of experience building applications for Linux and Windows systems. I focus on system architecture, custom web platforms, server infrastructure, and security-focused tools, with an emphasis on performance and reliability. Over the years, I have built everything from WordPress plugins and automation systems to full platforms, ad serving systems, monitoring tools, and API-driven applications. I prefer working close to the system, solving real problems, and building tools that are meant to be used.

Related Articles

Monitor SSL Expiration with Python

Monitor SSL Expiration with Python

SSL certificates are one of those systems that work quietly in the background until something goes wrong. When a certificate...

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Building a Network Tracker Auditor for Privacy with Python

Building a Network Tracker Auditor for Privacy with Python

In my last post, I dug into AdGuard, a robust ad blocker that tackles trackers and ads head-on. But how...

Next Post
Send Email with Python

Send Email with Python

Recommended Services

Latest Articles

Working With Webhooks in PHP

Working With Webhooks in PHP

I have used webhooks in a lot of different situations over the years, from payment alerts to form submissions to...

Read moreDetails

My Backup Setup for Linux PCs

My Backup Setup for Linux PCs

March 31st is World Backup Day. It is meant to be a reminder, but I do not rely on reminders...

Read moreDetails

Detecting Hidden WordPress Malware Disguised as Images

Detecting Hidden WordPress Malware Disguised as Images

With the recent discovery of malicious files like Stained_Heart_Red-600x500.png being found on servers across the web, it pushed me to...

Read moreDetails

Server-Side Image Conversion with Apache

Server-Side Image Conversion with Apache

I stopped relying on third party image services a while ago. They work, but they add cost, latency, and another...

Read moreDetails
  • Privacy Policy
  • Terms of Service

© 2025 JMooreWV. All rights reserved.

No Result
View All Result
  • Home
  • Guides
    • Linux
    • Programming
      • JavaScript
      • PHP
      • Python
    • Tools
    • WordPress
  • Blog
    • Artificial Intelligence
    • Tutorials
    • Privacy
    • Security
  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attack Stats
  • Contact
    • General Contact
    • Website Administration & Cybersecurity