Building RESTful API using R

I have two options for you:

plumber

plumber allows you to create a REST API by decorating your existing R source code with special comments.

A small example file:

# myfile.R

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

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

From the R command line:

> library(plumber)
> r <- plumb("myfile.R")  # Where 'myfile.R' is the location of the file shown above
> r$run(port=8000)

With this you would get results like this:

$ curl "http://localhost:8000/mean"
 [-0.254]
$ curl "http://localhost:8000/mean?samples=10000"
 [-0.0038]

Jug

Jug is a small web development framework for R which relies heavily upon the httpuv package. It’s main focus is to make building APIs for your code as easy as possible. It is not supposed to be either an especially performant nor an uber stable web framework. Other tools (and languages) might be more suited for that. It’s main focus is to easily allow you to create APIs for your R code. However, the flexibility of Jug means that, in theory, you could built an extensive web framework with it.

It very easy to learn and has a nice vignette.

An Hello-World-example:

library(jug)

jug() %>%
  get("/", function(req, res, err){
    "Hello World!"
  }) %>%
  simple_error_handler_json() %>%
  serve_it()

This is for those who want to have a comparion of API development with R - plumber, Rserve and rApache.

Basically concurrent requests are queued by httpuv in plumber so that it is not performant by itself. The author recommends multiple docker containers but it can be complicated as well as resource-demanding.

There are other tech eg Rserve and rApache. Rserve forks prosesses and it is possible to configure rApache to pre-fork so as to handle concurrent requests.

See the following posts for comparison

https://www.linkedin.com/pulse/api-development-r-part-i-jaehyeon-kim/ https://www.linkedin.com/pulse/api-development-r-part-ii-jaehyeon-kim/

Tags:

Rest

Api

R

Plumber