Deploying a Plumber API on AWS EC2 Instance

Danny Morris

2019/07/06

  1. Launch an EC2 instance using this AMI

  2. Connect to RStudio Sever on AWS EC2 Instance. See this post

  3. In RStudio Server, create a folder called plumber-apis (or something similar)

  4. Create two .R files sample-plumber.R and launch-sample-plumber.R

sample-plumber.R

# plumber.R

#* Echo back the input
#* @param msg The message to echo
#* @get /echo
function(msg=""){
  list(msg = paste0("The message is: '", msg, "'"))
}

#* Plot a histogram
#* @png
#* @get /plot
function(){
  rand <- rnorm(100)
  hist(rand)
}

#* Return the sum of two numbers
#* @param a The first number to add
#* @param b The second number to add
#* @post /sum
function(a, b){
  as.numeric(a) + as.numeric(b)
}

launch-sample-plumber.R

  1. SSH into the EC2 instance using Git Bash and install the plumber package. See this post
# launch R session
R -

# install plumber
install.packages("plumber")
  1. Exit R and cd into RStudio Server home
cd /home/rstudio/plumber-apps/

# In RStudio Server, run getwd() to find the home directory
  1. Run the launch-sample-plumber.R script to expose the API
R CMD BATCH launch-sample-plumber.R
  1. Invoke the API’s POST method from anywhere
# From a Rstudio desktop client...

library(httr)

request <- POST("http://ec2-18-224-95-116.us-east-2.compute.amazonaws.com:8000/sum?b=1&a=3")

content(request, "parsed")