Last active
June 8, 2021 14:18
-
-
Save ryanbthomas/9d4c8cf5e77e78f671ed41511f71ae54 to your computer and use it in GitHub Desktop.
Example of creating a plumber endpoint with multiple data types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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