knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  echo = TRUE
)

About Kolada API

In the municipal and county councils (Kolada) you can follow the municipalities and county councils activities year by year. With about 5,000 key figures, you get the basis for analysis and comparisons. In Kolada, we provide a collective input of key figures on resources, volumes and quality in all municipalities and county councils. Key ratios are often based on national statistics from the statistical authorities, but also on data from other sources. For example, most municipalities and county councils participate in voluntary reporting of quality in various activities in Koladas "input function". We follow and drive the development of new key figures, thus giving you access to Sweden's widest range of information about your business.

(Source: https://www.kolada.se/?_p=index/API )

library(httr)
library(jsonlite)
library(plyr)

# Basic Data
base = "http://api.kolada.se/"
api_version = "v2/"

#' Fetch Municipalities
#'
#' @return Returns a data.frame containing all municipalities.
#' @export
#'
fetchMunicipalities = function() {
  endpoint = "municipality"
  webCall = paste(base, api_version, endpoint, sep="")

  # Execution
  response = GET(webCall)

  # Check Server Response
  if (response["status_code"] < 200 | response["status_code"] > 299) stop("HTTP Stauts code it not OK (not in range 200-299).")

  # Deserialization
  result = fromJSON(content(response, "text", encoding = "utf-8"), flatten = TRUE)

  return(as.data.frame(result))
}

#' Fetch KPIs
#'
#' @return Returns a data.frame containing all KPIs with their id and description.
#' @export
#'
fetchKpis = function() {
  endpoint = "kpi_groups"
  webCall = paste(base, api_version, endpoint, sep="")

  # Execution
  response = GET(webCall)

  # Deserialization
  result = fromJSON(content(response, "text", encoding = "utf-8"), flatten = FALSE)

  # Check Server Response
  if (response["status_code"] < 200 | response["status_code"] > 299) stop("HTTP Stauts code it not OK (not in range 200-299).")

  # Prepare Data Frames
  kpi.group.data.frame = as.data.frame(result)
  kpi.data.frame = data.frame(member_id = integer(), member_title = character())

  # Extract required data
  for (i in 1:nrow(kpi.group.data.frame)) {
    group_kpi = kpi.group.data.frame[i, 3][[1]]
    kpi.data.frame = rbind(kpi.data.frame, group_kpi)
  }
  return(kpi.data.frame)
}

#' Fetch By Municipality
#'
#' @param municipality Id of the municipality.
#' @param year The year as integer.
#'
#' @return Returns a data.frame containing all KPIs belonging to the municipality in the given year.
#' @export
#'
fetchByMunicipality = function(municipality, year){
  #http://api.kolada.se/v2/data/municipality/1860/year/2009

  if (length(municipality) != 1 | !is.numeric(municipality)) stop("municipality parameter must be a numeric scalar.")
  if (!is.numeric(year) | !is.vector(year)) stop("year must be a numeric vector")

  endpoint = "data/municipality/"

  webCall = paste(base, api_version, endpoint, municipality, "/year/", sep="")

  for (i in 1:length(year)) {
    webCall = paste(webCall, year[i], sep = "")
    if (i != length(year)) webCall = paste(webCall, ",", sep="")
  }

  # Execution
  response = GET(webCall)

  # Check Server Response
  print(response)
  if (response["status_code"] < 200 | response["status_code"] > 299) stop("HTTP Stauts code it not OK (not in range 200-299).")

  # Deserialization
  result = fromJSON(content(response, "text"), flatten = TRUE)
  return(as.data.frame(result))
}

#' Fetch By KPI
#'
#' @param kpi Id of the KPIs as a list.
#' @param municipality Id of the municipality.
#' @param year The years to fetch as a vector
#'
#' @return Returns a data.frame containing the requested data
#' @export
#'
fetchByKpi = function(kpi, municipality , year = c()) {

  if (any(grepl("[,]", kpi) == TRUE)) stop("character ',' is not allowed for kpis")
  if (length(kpi) == 0) stop("kpi contains no entries")
  if (!is.list(kpi)) stop("kpi must be a list")
  if (!is.vector(year)) stop("year is not a vector")

  endpoint = "data/kpi/"

  webCall = paste(base, api_version, endpoint, sep="")

  for (i in 1:length(kpi)) {
    webCall = paste(webCall, kpi[i], sep="")
    if (i != length(kpi)) webCall = paste(webCall, ",", sep="")
  }

  webCall = paste (webCall, "/municipality/", municipality, sep="")

  if (length(year) > 0) {
    webCall = paste(webCall, "/year/", sep="")

    for (j in 1:length(year)) {
      webCall = paste(webCall, year[j], sep="")
      if (j != length(year)) webCall = paste(webCall, ",", sep="")
    }
  }

  # Execution
  response = GET(webCall)

  # Check Server Response
  if (response["status_code"] < 200 | response["status_code"] > 299) stop("HTTP Stauts code it not OK (not in range 200-299).")

  # Deserialization
  result = fromJSON(content(response, "text"), flatten = TRUE)
  if (result["count"] == 0) return(data.frame())
  return(as.data.frame(result))
}

Graphical User Interface

Let's have a look at the graphical user interface: https://imgur.com/FSSGgBf

You can select two KPI's to plot, one on the left hand side and one on the right hand side. With those two charts it's possible to compare the data of either different municipalities or KPIs. You can also specify a range of years to display. Once you've selected the data you want to display, click the button. The data is then fetched from the server and displayed. Keep in mind that not all combinations of KPIs and municipalities have data. In fact most of them don't. The preselected entries should work though. Once the data is loaded, you will also find a description of the KPI above the charts. The charts also include the median and the linear trend.

webService.R

This are the different methods provided by the webService.R file. This service is responsible for the communication with the server.

fetchMunicipalities

A method call that gives back a dataset with details about municipalities.

head(fetchMunicipalities())

fetchKpis

A method call that gives back a dataset with all member id's and the associated description.

head(fetchKpis())

fetchByMunicipality

A method call that returns a dataset with all values for the prespecified municipality and year.

head(fetchByMunicipality(1440, c(2012, 2013)))

fetchByKpi

A method call that gives back a dataset with all values for the prespecified kpis, municipality and year. In this example the kpi's "N00914" and "U00405" of the municipailty 1440 and year 2010, 2011 and 2012 are fetched. The method returns a data frame.

head(fetchByKpi(list("N00914", "U00405"), 1440, c(2010, 2011, 2012)))

Example API

If you like to see how the data looks like, you can simply open the following URL in a webbrowser (or send a HTTP GET request). Firefox has a nice interface for displaying JSON, so we recommend using Firefox for this.

http://api.kolada.se/v2/data/municipality/1860/year/2009



rubenjmunoz/advanced-r-programming-5 documentation built on May 13, 2019, 5:35 p.m.