R/current.R

Defines functions weatherstack_current

Documented in weatherstack_current

#' Real-time weather data
#'
#' @param api_key Your API access key, which can be found in your acccount dashboard.
#' @param location pass a single location
#' @param units this parameter to pass one of the unit identifiers ot the API:m for Metric(	temperature: Celsius); s for Scientific(temperature: Kelvin); f for Fahrenheit
#' @return datframe contain current weather information.
#' @export
#' @import jsonlite
#' @import httr
#' @import ggplot2
#' @import hrbrthemes
#' @examples
#' weatherstack_current("ba435151893f4b833c9b27ca6f28044f","New York","m")
#' weatherstack_current("ba435151893f4b833c9b27ca6f28044f","London, United Kingdom","f")

weatherstack_current <- function(api_key,location,units) {
  # setting up the url to access the api
  domain<- "http://api.weatherstack.com/"
  endpoint <- "current"
  params<-list(access_key =api_key,
               query=location,
               units=units)
  url <- modify_url(paste(domain,endpoint,sep =""),
                    query = params)
  #post request api
  resp<- POST(url)
  # try for proper API key and access
  if(resp$status_code==101){
    print("User supplied an invalid access key.")
    return (NULL)}
  else if(resp$status_code==404){
    print("User requested a resource which does not exist.")
    return (NULL)}
  #convert the data to json format
  resp_json <- fromJSON(content(resp, "text"),
                        flatten = TRUE)
  #convert to dataframe
  df<- as.data.frame(resp_json)
  df_t <- t(df)
  return(df_t)
}
Yuening-Li/weatherstack documentation built on Feb. 16, 2020, 5:42 a.m.