Jug: Easily Create R APIs

[This article was first published on FishyOperations, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Jug stands for Just Unified Galloping. Okay, okay, it’s just a play on words coming from a Flask (Python) background.

Jug is my attempt to create a simple small web framework that allows you to turn your (existing) R functions into an API. Having the wonderful httpuv package at my disposal made this very easy for me.

So, how does this work?

Let’s say I have the following function:

say_hello_to<-function(name) paste("Hello", name)

Sometimes you would be in a situation where you want to send a GET request to a server and let a function (let’s say the one above) return it’s result. Thus, I want to expose the above function to allow HTTP GET requests to acces it. Using Jug I could do something like this:

library(jug)

jug() %>%
  gett("/", decorate(say_hello_to)) %>%
  serve_it()

Serving the jug at http://127.0.0.1:8080

However, when I run this code and post a GET request to the URL, the following happens:

$ curl 127.0.0.1:8080
ERROR: argument "name" is missing, with no default

Obviously, because the function say_hello_to requires the parameter name. A second attempt has better results:

$ curl 127.0.0.1:8080/?name=Bart
Hello Bart

However, besides exposing exsting fuctions, Jug is quite flexible. It has a middleware system, which allows to build up a (http) web server layer by layer. For example:

my_first_name<-NULL
my_last_name<-NULL

jug() %>%
  postt("/", function(req, res){
    my_first_name<<-req$post$first_name
    my_last_name<<-req$post$last_name
    return(TRUE)
  }) %>%
  gett("/", function(req, res){
    paste("Hello",my_first_name, my_last_name)
  }) %>%
  serve_it()


$ curl --data "first_name=Bart&last_name=Blitzers" 127.0.0.1:8080
☺

$ curl http://127.0.0.1:8080
Hello Bart Blitzers

So, enough for now. More on this later…

A (very) early version can be found at github.com/Bart6114/jug.

To leave a comment for the author, please follow the link and comment on their blog: FishyOperations.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)