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.

Dependencies

Faculty 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 Faculty:

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)
  mean(data)
}

#* @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:

Deployment

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:

#!/bin/bash
exec R --vanilla CMD BATCH runapi.R

Then, create the API in Faculty 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.

Usage

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.my.faculty.ai/mean" --header "UserAPI-Key: 0pFGOmQ2mm8jQGtFoCmdk1b0KHmI6ftXaNMjcUYYMoMwI3Kt2q"
[-0.316]

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

$ curl "https://cube-10b05aee-c90d-4a55-ad14-3940eee3de9e.api.my.faculty.ai/mean?samples=10000" --header "UserAPI-Key: 0pFGOmQ2mm8jQGtFoCmdk1b0KHmI6ftXaNMjcUYYMoMwI3Kt2q"
[0.0075]

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.