Accessing OpenWeather API

Author

Logan

Introduction

This will be a walkthrough of accessing and making a call to Open Weather API. Open Weather provides real-time weather data for current, short-term, and long-term forecasting. This includes any location worldwide. This service can be helpful for anyone looking to analyze weather data. This may include, but is not limited to, service businesses looking to compare sales with historical weather data. For example, roofing companies can analyze their sales after days of high winds and use this API to better predict wind conditions, ensuring they have sufficient resources. Another example would be HVAC companies looking at weather data for extreme hot or cold weather to predict for AC or furnace calls.

In this walk through, we will only be pulling current weather data as that is what is available in the free version of Open Weather.

Setup

To access this API, the first step is to create an account at Openweathermap.com

Once an account is created, you are provided an API key and automatically given a free version for your account. Once you find the “Current Weather API Doc” on the product page, it shows the required parameters for the API URL. These include appid, latitude, and longitude. Optional parameters include mode, lang, and units, which I’ll use for this walk-through.

Before we can create our URL, we will load our libraries listed below as well as locate our coordinates for Cincinnati.

Coordinates

Open Weather provides a link to help establish coordinates…

http://api.openweathermap.org/geo/1.0/direct?q={city name},{state code},{country code}&limit={limit}&appid={API key}

Then we fill in the appropriate parameters, such as city name, state, country, limit, which can just be set to 5, and the API key that was given to you. To produce a URL that looks like

api.openweathermap.org/geo/1.0/direct?q=Cincinnati,Ohio,US&limit=5&appid={YOUR_API_KEY}

After putting this into a browser the coordinates will be given to to you at the bottom for the city you are trying to pull data for.

library(tidyverse) 
library(jsonlite)  
library(magrittr)  
library(httr) 
library(knitr)

URL Function

Now that we have our coordinates we will be able to create a function that generates the URL needed too access this Open Weather API. The parameters that I will be using are api_key (or appid), lat, lon, and units. The Open Weather endpoint can be found on their API doc. We will set the endpoint and parameters in the function, so they will just have to be filled out when the function is used. The function is shown below…

create_weather_url <- 
  function(api_key, lat, lon, units) {
    weather_endpoint <- "https://api.openweathermap.org/data/2.5/weather?"
    lat <- paste("lat=",lat, sep = "")
    lon <- paste("&lon=", lon, sep = "")
    units <- paste("&units=", units, sep = "")
    api_key <- paste("&appid=", api_key, sep = "")
    
    weather_url <- paste(weather_endpoint,lat,lon,units,api_key, sep = "")
    
    return(weather_url)
    
  }

Testing Function

Now we can go ahead and test the function we just created by filling out the parameters…

create_weather_url(api_key = "YOUR_API_KEY", #API key hidden
                   lat = "39.0913",
                   lon = "-84.5028",
                   units = "imperial")
[1] "https://api.openweathermap.org/data/2.5/weather?lat=39.0913&lon=-84.5028&units=imperial&appid=YOUR_API_KEY"

As you can see, we simply just had to type in the provided api key, lat, lon, and units to get our URL.

Request Function

Now we can request the data from the API itself by making another function to simplify our code for future calls.

request_weather_url_df <- 
  function(api_key, lat, lon, units) {
    
    weather_url <- 
      create_weather_url(api_key,lat,lon,units)
    
    weather_url_response <- 
     weather_url %>% 
     GET()
    
    weather_data <- 
     weather_url_response %>% 
     content(as = "text",
          encoding = "UTF-8") %>% 
     fromJSON() %>% 
     use_series(weather) #It had produced more fields inside the list could not figure out how to pull others into df. I think they were lists inside of lists
       
return(weather_data)
    }

Using the first function, I created a new request function that used the GET() command to “get” the data from API and then convert it into a data frame by specifying which portion of the API to convert in the use_series() command. Below we can test out the function with out parameters to see the data itself.

Data

id main description icon
800 Clear clear sky 01n

Conclusions

The result is a single-row data frame that shows current real-time weather data for the coordinates specified. The coordinates of the first URL provided the city of Newport, even though I specified Cincinnati, they are still very close. If I were to use this API again, I would use their forecast API, which is included in the free version, or pay for an inexpensive option to get better, more usable data.