jakob-r
jakob-r

Reputation: 7282

Serve downloadable files with plumber

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.

Upvotes: 3

Views: 1387

Answers (1)

jakob-r
jakob-r

Reputation: 7282

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)

Upvotes: 6

Related Questions