R/aviation.R

Defines functions fetch_aviation_airfare fetch_aviation_airport fetch_aviation_airport_schedule

Documented in fetch_aviation_airfare fetch_aviation_airport fetch_aviation_airport_schedule

#' Fetches other series from DataHub
#'
#'
#' @examples
#'
#' @export
fetch_aviation_airfare <- function(query = list()) {

  # Check input arguments
  collection <- checkmate::makeAssertCollection()
  checkmate::assertList(query, add = collection)
  checkmate::reportAssertions(collection)

  # Create url
  url <- paste0(
    getOption("base_path", default = "https://api.datahub.is"),
    "/aviation/airfare")

  # Make API call and parse
  resp <- httr::GET(
    url,
    httr::add_headers("Authorization" = getOption("authentication_key", default = "")),
    httr::accept("text/csv"),
    query = query)

  #parsed <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))
  parsed <- readr::read_csv(httr::content(resp, "text", encoding = "UTF-8"))

  check_error(resp)

  tryCatch({
    parsed$buy_date = as.Date(parsed$buy_date)
    parsed$departure_date = as.POSIXct(parsed$departure_date)
    parsed$arrival_date = as.POSIXct(parsed$arrival_date)
    return(parsed)
  },
  error=function(error_message) {
    return(data.frame())
  })
}




#' Fetches other series from DataHub
#'
#'
#' @examples
#'
#' @export
fetch_aviation_airport <- function() {

  # Create url
  url <- paste0(
    getOption("base_path", default = "https://api.datahub.is"),
    "/aviation/airport")

  # Make API call and parse
  resp <- httr::GET(
    url,
    httr::add_headers("Authorization" = getOption("authentication_key", default = "")),
    httr::accept_json())

  parsed <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))

  check_error(resp)

  tryCatch({
    return(parsed)
  },
  error=function(error_message) {
    return(data.frame())
  })
}



#' Fetches other series from DataHub
#'
#'
#' @param query
#'
#' @examples
#'
#' @export
fetch_aviation_airport_schedule <- function(query = list()) {

  # Check input arguments
  collection <- checkmate::makeAssertCollection()
  checkmate::assertList(query, add = collection)
  checkmate::reportAssertions(collection)

  query['airport_code'] <- 'KEF'

  # Create url
  url <- paste0(
    getOption("base_path", default = "https://api.datahub.is"),
    "/aviation/airport/schedule")

  # Make API call and parse
  resp <- httr::GET(
    url,
    httr::add_headers("Authorization" = getOption("authentication_key", default = "")),
    httr::accept_json(),
    query = query)

  parsed <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))

  check_error(resp)

  tryCatch({
    parsed$date = as.Date(parsed$date)
    return(parsed)
  },
  error=function(error_message) {
    return(data.frame())
  })
}
palmargisla/datahub-r documentation built on Sept. 18, 2019, 9:50 p.m.