Building RESTful API using R

B.Mr.W. picture B.Mr.W. · Jun 28, 2016 · Viewed 17.5k times · Source

I am thinking about building a RESTful API using the programming language R, mainly to expose my machine learning model to the user in an API format. I know there are some options like export to PMML, PFA and use other languages to take care of the API part. However, I want to stick to the same programming language and was wondering if there is anything like Flask/Django/Springbook framework in R?

I took a look at servr/shiny but I really don't think RESTful is what they are designed for. Is there any better solution within R that is more easy to use?

Answer

nnn picture nnn · Apr 13, 2017

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()