Skip to content

Instantly share code, notes, and snippets.

@ryanbthomas
Last active June 8, 2021 14:18
Show Gist options
  • Save ryanbthomas/9d4c8cf5e77e78f671ed41511f71ae54 to your computer and use it in GitHub Desktop.
Save ryanbthomas/9d4c8cf5e77e78f671ed41511f71ae54 to your computer and use it in GitHub Desktop.
Example of creating a plumber endpoint with multiple data types
#
# This is a Plumber API. You can run the API by clicking
# the 'Run API' button above.
#
# Find out more about building APIs with Plumber here:
#
# https://www.rplumber.io/
#
library(plumber)
library(tibble)
work <- function(seed) {
if (!is.null(seed)) {
set.seed(as.integer(seed))
}
tibble(val = rlnorm(100))
}
#* @param seed
#* @serializer unboxedJSON
#* @get /data
function(seed) {
work(seed)
}
#* @param seed
#* @get /data/<type>
function(res, type, seed) {
type <- tolower(type)
if (!type %in% c("json", "rds")) {
stop(type, " is an invalid endpoint. Valid endpoints are 'json' and 'rds'",
call. = FALSE)
}
x <- work(seed)
if (type == "rds") {
res$setHeader("content-type", "application/rds")
tmp <- tempfile()
saveRDS(x, file = tmp)
res$body <- readBin(tmp, "raw", n = file.info(tmp)$size)
return(res)
}
# default to JSON
res$setHeader("content-type", "application/json")
res$body <- jsonlite::toJSON(x, auto_unbox = TRUE)
return(res)
}
api <- plumber::plumb("api.R")
api$run(port = 8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment