Example: Creating an API from R code using plumber

This example demonstrates how to implement two simple API methods with the R package plumber, which allows you to create REST APIs from R code.


SherlockML API servers currently don’t come with R installed. However, we can install everything we need for an API in an environment (see Custom server environments). Simply paste the following into an environment called R API with plumber in SherlockML:

set -eu

sudo apt-get --quiet --assume-yes update

# install R and dependencies
sudo apt-get --quiet --assume-yes install r-base build-essential bzip2 libfontconfig1 libsm6 libxrender1 graphviz r-recommended libxml2-dev libcurl4-openssl-dev libssl-dev

# install plumber, a REST API package in R
R --vanilla -e "withCallingHandlers(install.packages(c('plumber'), repos='https://cran.rstudio.com/'), warning=function(w) stop(w))"

# set the required environment variables for R
    echo "# Start of export from /etc/container_environment.sh";
    cut -f 2- -d ' ' /etc/container_environment.sh;
    echo "# End of export from /etc/container_environment.sh";
} | sudo tee --append /etc/R/Renviron.site

R source code

We create our API by defining R functions that are decorated with plumber’s special comments. For the purposes of this example, we’ll assume you store the following code in /project/myapidirectory/myapi.R:

# myapi.R

#* @get /mean
normalMean <- function(samples=10){
  data <- rnorm(samples)

#* @post /sum
addTwo <- function(a, b){
  as.numeric(a) + as.numeric(b)

In addition, you will need to create a basic R script for running this API. Let’s assume you do this in the file /project/myapidirectory/runapi.R:

# runapi.R

r <- plumb("myapi.R")


Assuming that you store this file as runapi.R to /project/myapidirectory in your project workspace, to deploy the API create the following script at /project/myapidirectory/run.sh:

exec R --vanilla CMD BATCH runapi.R

Then, create the API in SherlockML with the settings:

  • Type: Custom
  • Working Directory: /project/myapidirectory
  • Script: run.sh
  • Environment: R API with plumber

Start a server under “Development”, and you can start querying your API.


To get an estimate of the mean of a normal distribution (the /mean method of our API), simply copy the URL of your API server, as well as the API key, to a curl command like this:

$ curl "https://cube-10b05aee-c90d-4a55-ad14-3940eee3de9e.api.sherlockml.io/mean" --header "SherlockML-UserAPI-Key: 0pFGOmQ2mm8jQGtFoCmdk1b0KHmI6ftXaNMjcUYYMoMwI3Kt2q"

We can pass parameters in our API call, as well:

$ curl "https://cube-10b05aee-c90d-4a55-ad14-3940eee3de9e.api.sherlockml.io/mean?samples=10000" --header "SherlockML-UserAPI-Key: 0pFGOmQ2mm8jQGtFoCmdk1b0KHmI6ftXaNMjcUYYMoMwI3Kt2q"

Of course, you can use any requests tool, such as Postman, to query your API.

For more information on how to create an API that returns files or accepts payloads, take a look at the official plumber documentation.