OpenWeather API Usage

Author

Daniel

OpenWeather Map

OpenWeatherMap is an online service, owned by OpenWeather Ltd, that provides global weather data via API, including current weather data, forecasts, nowcasts, and historical weather data. We are going to focus on how to use an API to get the weather data for a couple of states around the world

library(httr)
library(jsonlite)
library(dplyr)
library(magrittr)
library(knitr)

Getting your API

To get your api you would have to create or sign-in to an OpenWeather account. After logging in, go to the API Keys section of your account dashboard. Generate a new API key. This key will be used to authenticate your requests to the API.

Fetching Weather Data

Once you have your API key, you can begin making requests. Below is an example of how to fetch weather data for a specific location.

Defining the API URL

To build the API URL, you need the following:

  • Your API key

  • The latitude and longitude of the desired location

api_key <- api_key
latitude <- "6.465422" # Example Lagos 
longitude <-"3.406448" # Example Lagos 
  weather_api_url <- paste0(
    "https://api.openweathermap.org/data/2.5/weather?lat=", 
    latitude, "&lon=", longitude, "&appid=", api_key, "&units=metric"
  ) # paste0() function to concatenate several strings into a single string

Make a GET Request

The GET() function sends the request to OpenWeatherMap.

weather_response <- GET(weather_api_url)

Check for Success

  • You can check the status of your request by examining the status code:

    • 200: Success

    • 404: Not found

    • 401: Unauthorized

    • 403: Forbidden

    • 429: Too many requests

    • 500: Server error

    • 503: Busy server

weather_response$status_code == 200 #SUCCESS!!
[1] TRUE

JSON

We use fromJSON() to convert the JSON data to an R list or dataframe.

weather_data <-
  weather_response %>% 
  content(as = "text",
          encoding = "UTF-8") %>%
  fromJSON()

Extraction

We extract what we need from the response, In this scenario I’m extracting The name of the city, the windspeed, the temperature, what the temperature feels like, and the humidity

lagos <- 
  weather_data%>% 
  use_series(weather) %>% 
  mutate(city = weather_data$name,
         windspeed = weather_data$wind$speed,
         temp = weather_data$main$temp,
         feels = weather_data$main$feels_like,
         humidity = weather_data$main$humidity)

Function

Imagine having to do all this steps for 10 cities : (

We can create a function that allows us to only enter our api, longitude, latitude for the city we are looking for

get_weather_data <- function(api_key, latitude, longitude) {
  
  # Create the URL for the API request
  weather_api_url <- paste0(
    "https://api.openweathermap.org/data/2.5/weather?lat=", 
    latitude, "&lon=", longitude, "&appid=", api_key, "&units=metric"
  )
  
  # Send the GET request to the API
  weather_response <- GET(weather_api_url)
  
  # Extract JSON content
  weather_data <- content(weather_response, as = "text", encoding = "UTF-8") %>% fromJSON()
  
  weather <- weather_data %>%
    use_series(weather) %>%
    mutate(
      city = weather_data$name,
      windspeed = weather_data$wind$speed,
      temp = weather_data$main$temp,
      feels = weather_data$main$feels_like,
      humidity = weather_data$main$humidity
    )
  
}

Example: Fetching Weather Data for Multiple Cities using our function

You can now use the get_weather_data() function to fetch weather data for various cities:

lagos <- get_weather_data(api_key, "6.465422", "3.406448")  # Lagos
durban <- get_weather_data(api_key, "-29.883333", "31.049999")  # Durban
johannesburg <- get_weather_data(api_key, "-26.195246", "28.034088")  # Johannesburg
accra <- get_weather_data(api_key, "5.614818", "-0.205874")  # Accra
cairo <- get_weather_data(api_key, "30.033333", "31.233334")  # Cairo

# Combine data from all cities into one dataframe
africa <- bind_rows(lagos, durban, johannesburg, accra, cairo)


kable(africa)
id main description icon city windspeed temp feels humidity
500 Rain light rain 10n Lagos 1.03 24.18 25.11 94
501 Rain moderate rain 10n Point 3.57 18.17 18.24 84
800 Clear clear sky 01n Johannesburg 0.51 12.00 10.72 56
500 Rain light rain 10n Dome 4.63 27.16 31.08 89
800 Clear clear sky 01n Al ’Atabah 5.14 19.38 18.91 59

Conclusion

This tutorial shows how to use the OpenWeatherMap API to fetch weather data for various cities. By creating a reusable function, we simplified the process for multiple locations.