How to build an API in R

Hadrien Dykiel
3 min readNov 18, 2019

--

Not too long ago, it was difficult for R programmers to share their models, plots, or functions with other services. For example, the task of taking a model developed in R and having a website built with say, Javascript, query that model and receive a standard JSON or XML response containing the prediction results was no easy feat. A lot of time and resources was often spent converting these R models into Java or some other programming language that could then be turned into an API.

All of that changed when, in June of 2018, the first version of the plumber package was released. This genius little package is an API generator for R, giving you the ability to generate APIs from R functions by simply adding a few special comments to your code. Here are a few examples of how plumber might be used in the real word:

  • A real estate company builds a very complex (and accurate) model in R which estimates the market value of homes based on hundreds of different variables. By sharing this model via a plumber API, their Android and iOS mobile applications can now query that API and share the estimated value for any property with the user.
  • An insurance company creates a Plumber API to allow 3rd party brokers to integrate with the insurance company’s systems and alert them anytime a new policy is written. The insurance company can now monitor bound policies in real-time, rather than having to rely on manual reports.
  • A sales team creates a market intelligence report containing many visualizations, and decides to share those plots via an API. Folks at the company can now share updated versions of these plots with one another via their internal messaging platform, such as Slack.

Plumber API example

Here is a simple example which you can try yourself:

Step 1: install and load the plumber package by running the commands install.packages("plumber") and library(plumber).

Step 2: create an R script and write whatever function you want. For this example, I decided to write a simple function that approximates the amount of carbon dioxide emitted into the atmosphere for every kilometer traveled by plane:

plumber.R

calculate_emissions <- function(transport_mode = “plane”, kilometers = 1) {if (transport_mode == “plane”) {
CO2_grams <- 175*kilometers # C02 grams
CO2_kg <- CO2_grams/1000
CO2_ton <- CO2_kg/1000
return(CO2_ton)
} else {stop(“please enter a valid transportation mode”) }
}

You can call your R script whatever you want, although the convention is to call it plumber.R so that’s what we’ll do.

Step 3: transform your R script into a plumber API! We’ll do this by adding special comments, or annotations, using the syntax #* rather than the usual # used for regular comments. You can also use the syntax #', if you prefer. We will use these special comments to give the API a name, add a description, define the query parameters, and name the API endpoint:

#* @apiTitle Emissions Calculator#* Estimate your CO2 footprint
#* @param kilometers Kilometers traveled
#* @get /emissions
function(kilometers, transport_mode = "plane") {

if (transport_mode == "plane") {
CO2_grams <- 175*as.numeric(kilometers) # C02 grams
CO2_kg <- CO2_grams/1000
CO2_ton <- CO2_kg/1000
return(CO2_ton)
} else {

stop("please enter a valid transportation mode")

}
}

You can run this API locally by clicking on the “Run API” button in the RStudio IDE, or by running the command plumb(file = "your-file-path/plumber.R")$run(). The plumber package will then use your special comments to generate the API. @apiTitle is optional, but if you do give your API a title make sure to have a blank space after it. The special comment we added it after it is also optional. We used @param to define each parameter the API will accept, which will typically be whatever your function arguments are. Finally, we defined our API endpoint as /emissions and chose to use the GET request method using @get. Plumber also supports other HTTP request methods such as POST, PUT, DELETE, and HEAD.

And voila. We’ve successfully transformed our R function into a web API by simply adding a couple special comments to our script. We also ran our API locally to see it and try it out ourselves. Now all that’s left to do it to publish it to a server so other applications can leverage it.

--

--