Python


Python is a programming language that is considered easy for beginners, but still hard to master.

I definitely think it is one of the most beautiful languages to write code in. It is possible to create websites with the Flask framework as well, which is simply amazing.
This time we want to start easy and try to gain some weather data. In order to do this, you will have to create an account and generate a token on the OpenWeatherMap website.

After doing so, we can begin to code!



First, I need to define the shebang and import the required libraries. The shebang indicates that the following script is coded in Python and the imported packages make sure that I can call the API, print the data nicely and exit the script if any errors occur.

#!/usr/bin/env python3

# We import requests to call the OpenWeatherMap API.
import requests
# We import json in order to retrieve the data in a json format.
import json
# We import sys to end the script as clean as possible, e.g. if the API is unavailable.
import sys

I create a function to call the API and implement useful error handling. If I can't connect to the API or our API key is not correct, the corresponding error is printed. I then return the data in a json format.

def gettingweatherdata():

    api_key = "<123456789>" # put your API Token here
    lat = "<12.34>" # put your latitude value here
    lon = "<56.78>" # put your longitude value here
    
    url = "https://api.openweathermap.org/data/2.5/onecall?lat=%s&lon=%s&appid=%s&units=metric" % (lat, lon, api_key)

    try:
        response = requests.get(url)
    except requests.exceptions.ConnectionError:
        print("No connection to URL")
        sys.exit()

    if not response.status_code == 200:
        print("Error - No API Key")
        sys.exit()
    else:
        data = json.loads(response.text)

    return data

I then sort the data - if OpenWeatherMap changes their dictionary keys, I just have to change them once in our script and not multiple times.

def weatherdata():

    data = gettingweatherdata()
    entry = data["current"]

    sortData = {"Temperature" : entry["temp"],
                "Feels like"  : entry["feels_like"],
                "Wind Speed"  : entry["wind_speed"],
                "UV Index"    : entry["uvi"],
                "Weather"     : entry["weather"][0]["main"]
    }

    return sortData

if __name__ == "__main__":
    
    print(weatherdata())

Finally I can see our weather data in a structured format.

{
  "Temperature": "26.74", 
  "Feels like": "24.44",
  "Wind Speed": "8.6",
  "UV Index": "6.2", 
  "Weather": "Sunny"
}

If you make sure you put in the correct data, you get your weather data for your location. That's very nice!



Navigate to Python II to learn how this data can be sent to you hourly.