Share your Models with R {plumber} APIs

How much do lemurs weigh?

  • You’ve built a great model

  • You want others to be able to use it

  • … without R

Baby ring tailed lemur being held by two gloved hands.

Image from Duke Lemur

What is an API?

  • Application Programming Interface

  • Standardised way for computers to communicate

  • Can be called anywhere from internet access

REST API - Author: Seobility - License: CC BY-SA 4.0

Example of APIs

  • LastFM
  • Weather
  • Electricity pricing
  • Statistics.gov.scot

Why create an API?

  • Make your R code more accessible

  • Allows real time interactivity with other technologies

  • Increases the impact of an analysis

  • Easy to scale the reach of your work

How?

The {plumber} package turns functions into API endpoints

  1. Write an R function
  2. Decorate it with special comments
  3. Plumb it
  4. Deploy it

A black hexagon, with the word plumber made out of pipes

1. Write an R function

lemur_weight = function(age){
  lemurs <- readr::read_csv("lemurs.csv")
  fit <- lm(weight_g ~ age_at_wt_mo, data = lemurs)
  new <- data.frame(age_at_wt_mo = as.numeric(age))
  weight <- predict.lm(fit, newdata = new)/1000
  return(weight)
}

2. Add special comments

```{r}
library(plumber)

#* Predict the weight of the lemur (kg) given it's age (months)
#* @get /

lemur_weight = function(age){
  lemurs <- readr::read_csv("lemurs.csv")
  fit <- lm(weight_g ~ age_at_wt_mo, data = lemurs)
  new <- data.frame(age_at_wt_mo = as.numeric(age))
  weight <- predict.lm(fit, newdata = new)/1000
  return(weight)
}
```

3. Plumb it

  • Run API button

  • Generates a user interface

  • Query it locally

    • curl request
    • httr::get

4. Host the API

  • Your code needs to run somewhere
  • Sharing it with others
  • RStudio Connect

Try it for yourself

rss-lemurs.jmpr.io/?age=24

rss-hadley.jmpr.io

Female collared lemur eating leaves.

Image from Duke Lemur

Learn More