APIs from R models with plumber

Let’s assume you’ve written a complex model in R that can predict whether a person is a cat person or a dog person:

cats.vs.dogs <- function(firstName, lastName) {
  if (lastName %in% c('Schrodinger', 'Schrödinger', 'Schroedinger')) {
    return('cat')
  }
  else {
    return('dog')
  }
}

In order to deploy this model as an API, we are going to use plumber, an R framework that parses code and turns functions decorated with special comments into API endpoints.

Save the following in a file called api.R in the root of your project:

# api.R

#' @post /predict
cats.vs.dogs <- function(firstName, lastName) {
  if (lastName %in% c('Schrodinger', 'Schrödinger', 'Schroedinger')) {
    return('cat')
  }
  else {
    return('dog')
  }
}

We can now create our API. Go to the APIs page for your project in Faculty and create a new API. You will be asked to choose a name, a domain name and a type for your API. For type, choose Plumber (R). Your domain name needs to be unique across all of Faculty. I suggest a domain name like cats-vs-dogs-2118, where you replace 2118 with a random string of your choice.

In the API settings page, change the working directory to /project, and the plumber file to api.R. You can leave the environments dropdown empty.

After you have your API set up, you can test and ultimately deploy it. Head to Test your API to find out how to go about the testing process.

Once you are familiar with the API development process, you may want to write a more complex API. Take a look at these examples below for inspiration: