library(plumber)
about <- function(req, res) {
info <- list(
version = "0.1.0",
creator = c("Me", "others"),
contact = "info@me.com",
description = "This is a dummy API"
)
info
}
# Create the Plumber router
pr() %>%
pr_get(
path = "/about",
handler = about
) %>%
pr_run()
However, I would like the user to have the option to specify the format of the content. e.g. http://127.0.0.1:4730/about?format=json or http://127.0.0.1:4730/about?format=rds
library(plumber)
about <- function(req, res) {
info <- list(
version = "0.1.0",
creator = c("Me", "others"),
contact = "info@me.com",
description = "This is a dummy API"
)
info
}
# Create the Plumber router
pr() |>
pr_get(
path = "/about",
handler = about
) |>
pr_get(
path = "/about/json",
handler = about,
seriealizer = serializer_json()
) |>
pr_get(
path = "/about/rds",
handler = about,
serializer = serializer_rds()
) |>
pr_run()
The other way would be to dynamically modify the endpoint serializer or manually serialize the response and returning a PlumberResponse. I find it more straightforward to provide different endpoints for different response type.
Thanks for your quick response.
I had seen the multiple endpoint one as well, but I would prefer use and argument instead of a whole different endpoint.
Thanks to some of the keywords you provided I was able to come up with this:
library(plumber)
library(jsonlite)
toReturn <- function(req, res, val, format = "json"){
if(format == "text"){
res$setHeader("Content-Type", "text")
res$body = paste(as.character(val), collapse = " ")
} else if(format == "json") {
res$setHeader("Content-Type", "application/json")
res$body <- toJSON(val)
} else {
res$status <- 400
res$body <- sprintf("Error: %s is not a supported format.", format)
}
res
}
about <- function(req, res) {
info <- list(
version = "0.1.0",
creator = c("Me", "others"),
contact = "info@me.com",
description = "This is a dummy API"
)
toReturn(req, res, info, format)
}
pr() %>%
pr_get(
path = "/about",
handler = about) %>%
pr_run()
It works but I'm curious if you think this is valid or rather a hack ...