Serve downloadable files with plumber

Viewed 940

How can I set up my plumber API so that it serves a downloadable file?

For instance I would like to pass an rds or RData object directly rather then serializing it to JSON.

1 Answers

It is important to use the right serializer:

# If the URL gets called the browser will automatically download the file.
#' @serializer contentType list(type="application/octet-stream")
#' @get /rds
rest_rds = function() {
  tfile = tempfile()
  saveRDS(iris, file = tfile)
  readBin(tfile, "raw", n = file.info(tfile)$size)
}

After serving this plumber script you can download this object and import it in a separate R-session as follows:

tfile = tempfile()
download.file("http://127.0.0.1:7983/rds", destfile = tfile)
d_iris = readRDS(tfile)
Related