Connecting to APIs with R

With millions of APIs with data available, it would be a shame to miss out. How do you connect to an API and fetch data in R? This script will:

  • Connect to an API with schools in Skövde municipality, Sweden. The data set is found on the EU data portal.
  • Flatten the data
  • Manage the attributes
  • Convert the coordinates to geometry (points)
  • View the result on a map and colour code the schools by type

Code:

# Load libraries
library(dplyr)
library(httr)
library(jsonlite)
library(mapview)
library(sf)

# Create API call
API_URL <- 'https://skovde.entryscape.net/rowstore/dataset/d962e3df-9882-46e5-ba4f-79d029abef91/json'

# Make API call
raw_data <- GET(API_URL)

# Flatten
schools_list <- fromJSON(rawToChar(raw_data$content), flatten = TRUE)

# View data
#View(schools_list)

# To data frame
schools <- schools_list$results
#head(schools[ , c("name", "type", "street", "lat", "long")])

# Remove a few attributes
schools = select(schools, name, type, street, lat, long)

# Convert to points
schools_points = st_as_sf(schools, coords = c("long", "lat"), crs = 4326)

# View schools on map
mapview(schools_points, zcol = "type")

In case you use the same data and wonder about the Swedish school type abbreviations: FS = preschool, GR = elementary school and GY = gymnasium.

We´ll get back to using this metod later on in larger applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait