RStats - Plumber launcher script

Plumber Launcher Script

I use Jeff Allen’s Plumber a lot. If you haven’t seen it and want to start writing APIs in R, I’d strongly encourage you to check it out.

Jeff’s documentation tells you how to start the API that you’ve written, with the following code:

> library(plumber)
> r <- plumb("myfile.R")  # Where 'myfile.R' is the path to your plumber file
> r$run(port=8000)

This is fine if you’re working directly in RStudio and want to start your API endpoints running, but what about in a production environment?

In a production setting you need something that’s simple to use and easily repeatable. I use the following simple script in all of my production deployments:

#!/usr/bin/env Rscript
args <- commandArgs(trailingOnly = TRUE)
if ([1])) {
        cat('Missing file name\n')
} else {
        file <- args[1]
if ([2])) {
        cat('No port specified - defaulting to 8080\n')
        port <- 8080
} else {
        port <- as.numeric(args[2])
r <- plumb(file)

If you save this file as plumberStart.R and make sure it’s executable (with chmod +x plumberStart.R) then you can use it to launch plumber based APIs as follows:

$ ./plumberStart.R /path/to/plumber/file.R <port>

This will launch your API on the specified port. If the port is omitted, the script will use port 8080 as a default.

Obviously this will only work on Linux/Mac, but is particularly useful when combined with pm2, as detailed in the hosting section of the plumber docs.

Hopefully this will help others looking to move their plumber API deployments towards a production environment.