Assignment 5: Weather API

Author

Emma Black

About OpenWeather

OpenWeather provides access to historical weather data, current weather data, and future weather forecasts. This information is useful to a variety of industries and agencies. For example, a natural gas company’s revenue is directly tied to fluctuations in temperature, so having access to weather information allows for accurate profit forecasting. Additionally, weather data can be used to predict natural disasters and evacuate people prior to their arrival.

How to Use OpenWeather’s API

Step 1:

Go to https://openweathermap.org/api and click “Sign Up” at the top of the page to request a free API key using your email. Note that historical weather data and the 16 day forecast are not available with the free subscription level, so for this example I will be using the current weather endpoint.

Step 2:

Go to https://openweathermap.org/current to familiarize yourself with the API fields and parameters for the current weather endpoint.

Go to https://openweathermap.org/api/geocoding-api to familiarize yourself with the geocoding tool used by the API. This tool allows users to input information about the city they would like to examine, then it uses that information to provide the API with the latitude and longitude coordinates that it needs to function.

Step 3:

Assemble your API key, chosen endpoint, fields, and location using the following script.

#### Load packages ####
library(tidyverse)
library(jsonlite)
library(magrittr)
library(httr)
library(knitr)

#### Defining the API call URL ####

api_key <- api_key

current_weather_endpoint <- "https://api.openweathermap.org/data/2.5/weather?"

# This is from the geocoding tool provided by the service.
# The APIs require lat/long, but this can be used to decode the city location into coordinates
q<-"&q=Cincinnati" 

# Change the default output units to imperial instead of kelvin.
units <- "&units=imperial"

#### Create an API URL call ####
# Define the URL
current_weather_api_url <- 
  paste(current_weather_endpoint,api_key,q,units,sep = "")

#### Retrieving data from the API ####
weather_data_list <- 
  current_weather_api_url %>% 
  GET() %>% 
  content(as = "text",
          encoding = "UTF-8") %>% 
  fromJSON()

# Organizing the JSON result into a structured data frame object
current_weather_df <- 
  weather_data_list %>% 
  use_series(weather) %>% 
  mutate(city = weather_data_list$name,
         longitude = weather_data_list$coord$lon,
         latitude = weather_data_list$coord$lat,
         windspeed = weather_data_list$wind$speed,
         temp = weather_data_list$main$temp,
         humidity = weather_data_list$main$humidity) %>% 
  relocate(city)

Example of a Call to the OpenWeather API

Create a function that allows users to input the parameters they would like to search for.

create_url_function <- 
  function(endpoint,api_key,location,units){
  
    endpoint <- "https://api.openweathermap.org/data/2.5/weather?"
    
    api_key <- 
      paste("appid=",api_key,sep ="")
    
    location <- 
      paste("&q=", location, sep = "")
    
    units <- 
      paste("&units=",units, sep = "")
    
    combined_url <- 
      paste(current_weather_endpoint,api_key,location,units,sep = "")
    return(combined_url)
  }

Test out the function

create_url_function(endpoint = "https://api.openweathermap.org/data/2.5/weather?",
                    api_key = emma_api_key,
                    location = "Columbus",
                    units = "imperial")
[1] "https://api.openweathermap.org/data/2.5/weather?appid=744768eeb2d31fb01b5857f4428cbd88&q=Columbus&units=imperial"

Use the URL created by the function to create a new function that will produce a data frame.

url_df <- 
  function(endpoint,api_key,location,units) {
    
    combined_url <- 
      create_url_function(endpoint,api_key,location,units)
    
    weather_data_list <-  
      combined_url %>% 
      GET() %>% 
      content(as = "text",
              encoding = "UTF-8") %>% 
      fromJSON()
    
   current_weather_df <- 
    weather_data_list %>% 
    use_series(weather) %>% 
    mutate(city = weather_data_list$name,
           windspeed = weather_data_list$wind$speed,
           temp = weather_data_list$main$temp,
           humidity = weather_data_list$main$humidity) %>% 
   relocate(city)
   return(current_weather_df)
  }

Test out your final function

cbus_weather <- 
  url_df(endpoint = "https://api.openweathermap.org/data/2.5/weather?",
                    api_key = emma_api_key,
                    location = "Columbus",
                    units = "imperial")

cbus_weather %>% 
  data.frame() %>% 
  kable(caption = "Columbus Weather Data", align = 'c')
Columbus Weather Data
city id main description icon windspeed temp humidity
Columbus 801 Clouds few clouds 02d 16.11 77.68 36