Package Plumber Router
Package Plumber Router
plumber::Hookable -> Plumber
endpointsplumber router endpoints read-only
filtersplumber router filters read-only
mountsplumber router mounts read-only
environmentplumber router environment read-only
routesplumber router routes read-only
new()Create a new Plumber router
Plumber$new(file = NULL, filters = defaultPlumberFilters, envir)
filepath to file to plumb
filtersa list of Plumber filters
enviran environment to be used as the enclosure for the routers execution
A new Plumber router
run()Start a server using plumber object.
See also: pr_run()
Plumber$run(
host = "127.0.0.1",
port = getOption("plumber.port", NULL),
swagger = deprecated(),
debug = deprecated(),
swaggerCallback = deprecated()
)hosta string that is a valid IPv4 or IPv6 address that is owned by this server, which the application will listen on. "0.0.0.0" represents all IPv4 addresses and "::/0" represents all IPv6 addresses.
porta number or integer that indicates the server port that should be listened on. Note that on most Unix-like systems including Linux and Mac OS X, port numbers smaller than 1025 require root privileges.
This value does not need to be explicitly assigned. To explicitly set it, see options_plumber().
swaggerDeprecated. See $setDocs(docs) or $setApiSpec()
debugDeprecated. See $setDebug()
swaggerCallbackDeprecated. See $setDocsCallback()
mount()Mount a Plumber router
Plumber routers can be <U+201C>nested<U+201D> by mounting one into another
using the mount() method. This allows you to compartmentalize your API
by paths which is a great technique for decomposing large APIs into smaller files.
See also: pr_mount()
Plumber$mount(path, router)
patha character string. Where to mount router.
routera Plumber router. Router to be mounted.
\dontrun{
root <- pr()users <- Plumber$new("users.R") root$mount("/users", users)
products <- Plumber$new("products.R") root$mount("/products", products) }
unmount()Unmount a Plumber router
Plumber$unmount(path)
patha character string. Where to unmount router.
registerHook()Register a hook
Plumber routers support the notion of "hooks" that can be registered to execute some code at a particular point in the lifecycle of a request. Plumber routers currently support four hooks:
preroute(data, req, res)
postroute(data, req, res, value)
preserialize(data, req, res, value)
postserialize(data, req, res, value)
data
parameter that is created as a temporary data store for each request. Hooks
can store temporary data in these hooks that can be reused by other hooks
processing this same request.One feature when defining hooks in Plumber routers is the ability to modify
the returned value. The convention for such hooks is: any function that accepts
a parameter named value is expected to return the new value. This could
be an unmodified version of the value that was passed in, or it could be a
mutated value. But in either case, if your hook accepts a parameter
named value, whatever your hook returns will be used as the new value
for the response.
You can add hooks using the registerHook method, or you can add multiple
hooks at once using the registerHooks method which takes a name list in
which the names are the names of the hooks, and the values are the
handlers themselves.
See also: pr_hook(), pr_hooks()
Plumber$registerHook(
stage = c("preroute", "postroute", "preserialize", "postserialize", "exit"),
handler
)stagea character string. Point in the lifecycle of a request.
handlera hook function.
\dontrun{
pr <- pr()
pr$registerHook("preroute", function(req){
cat("Routing a request for", req$PATH_INFO, "...\n")
})
pr$registerHooks(list(
preserialize=function(req, value){
print("About to serialize this value:")
print(value)# Must return the value since we took one in. Here we're not choosing # to mutate it, but we could. value }, postserialize=function(res){ print("We serialized the value as:") print(res$body) } ))
pr$handle("GET", "/", function(){ 123 }) }
handle()Define endpoints
The <U+201C>handler<U+201D> functions that you define in these handle calls are identical to the code you would have defined in your plumber.R file if you were using annotations to define your API. The handle() method takes additional arguments that allow you to control nuanced behavior of the endpoint like which filter it might preempt or which serializer it should use.
See also: pr_handle(), pr_get(), pr_post(), pr_put(), pr_delete()
Plumber$handle( methods, path, handler, preempt, serializer, parsers, endpoint, ... )
methodsa character string. http method.
patha character string. Api endpoints
handlera handler function.
preempta preempt function.
serializera serializer function.
parsersa named list of parsers.
endpointa PlumberEndpoint object.
...additional arguments for PlumberEndpoint creation
\dontrun{
pr <- pr()
pr$handle("GET", "/", function(){
"<html><h1>Programmatic Plumber!</h1></html>"
}, serializer=plumber::serializer_html())
}
removeHandle()Remove endpoints
Plumber$removeHandle(methods, path, preempt = NULL)
methodsa character string. http method.
patha character string. Api endpoints
preempta preempt function.
print()Print representation of plumber router.
Plumber$print(prefix = "", topLevel = TRUE, ...)
prefixa character string. Prefix to append to representation.
topLevela logical value. When method executed on top level
router, set to TRUE.
...additional arguments for recursive calls
A terminal friendly representation of a plumber router.
serve()Serve a request
Plumber$serve(req, res)
reqrequest object
resresponse object
route()Route a request
Plumber$route(req, res)
reqrequest object
resresponse object
call()httpuv interface call function. (Required for httpuv)
Plumber$call(req)
reqrequest object
onHeaders()httpuv interface onHeaders function. (Required for httpuv)
Plumber$onHeaders(req)
reqrequest object
onWSOpen()httpuv interface onWSOpen function. (Required for httpuv)
Plumber$onWSOpen(ws)
wsWebSocket object
setSerializer()Sets the default serializer of the router.
See also: pr_set_serializer()
Plumber$setSerializer(serializer)
serializera serializer function
\dontrun{
pr <- pr()
pr$setSerializer(serializer_unboxed_json())
}
setParsers()Sets the default parsers of the router. Initialized to c("json", "form", "text", "octet", "multi")
Plumber$setParsers(parsers)
parsersCan be one of:
A NULL value
A character vector of parser names
A named list() whose keys are parser names names and values are arguments to be applied with do.call()
A TRUE value, which will default to combining all parsers. This is great for seeing what is possible, but not great for security purposes
If the parser name "all" is found in any character value or list name, all remaining parsers will be added.
When using a list, parser information already defined will maintain their existing argument values. All remaining parsers will use their default arguments.
Example:
# provide a character string parsers = "json"
# provide a named list with no arguments parsers = list(json = list())
# provide a named list with arguments; include `rds` parsers = list(json = list(simplifyVector = FALSE), rds = list())
# default plumber parsers parsers = c("json", "form", "text", "octet", "multi")
set404Handler()Sets the handler that gets called if an incoming request can<U+2019>t be served by any filter, endpoint, or sub-router.
See also: pr_set_404()
Plumber$set404Handler(fun)
funa handler function.
\dontrun{
pr <- pr()
pr$set404Handler(function(req, res) {cat(req$PATH_INFO)})
}
setErrorHandler()Sets the error handler which gets invoked if any filter or endpoint generates an error.
See also: pr_set_404()
Plumber$setErrorHandler(fun)
funa handler function.
\dontrun{
pr <- pr()
pr$setErrorHandler(function(req, res, err) {
message("Found error: ")
str(err)
})
}
setDocs()Set visual documentation to use for API
See also: pr_set_docs(), register_docs(), registered_docs()
Plumber$setDocs(docs = getOption("plumber.docs", TRUE), ...)docsa character value or a logical value. See pr_set_docs() for examples.
If using options_plumber(), the value must be set before initializing your Plumber router.
...Other params to be passed to docs functions.
setDocsCallback()Set a callback to notify where the API's visual documentation is located.
When set, it will be called with a character string corresponding
to the API docs url. This allows RStudio to open swagger docs when a
Plumber router pr_run() method is executed.
If using options_plumber(), the value must be set before initializing your Plumber router.
See also: pr_set_docs_callback()
Plumber$setDocsCallback(callback = getOption("plumber.docs.callback", NULL))callbacka callback function for taking action on the docs url. (Also accepts NULL values to disable the callback.)
setDebug()Set debug value to include error messages
See also: $getDebug() and pr_set_debug()
Plumber$setDebug(debug = interactive())
debugTRUE provides more insight into your API errors.
getDebug()Retrieve the debug value.
See also: $getDebug() and pr_set_debug()
Plumber$getDebug()
filter()Add a filter to plumber router
See also: pr_filter()
Plumber$filter(name, expr, serializer)
namea character string. Name of filter
expran expr that resolve to a filter function or a filter function
serializera serializer function
setApiSpec()Add a function to customize what is returned in $getApiSpec().
Note, the returned value will be sent through serializer_unboxed_json() which will turn all length 1 vectors into atomic values.
To force a vector to serialize to an array of size 1, be sure to call as.list() on your value. list() objects are always serialized to an array value.
See also: pr_set_api_spec()
Plumber$setApiSpec(api = NULL)
apiThis can be
an OpenAPI Specification formatted list object
a function that accepts the OpenAPI Specification autogenerated by plumber and returns a OpenAPI Specification formatted list object.
The value returned will not be validated for OAS compatibility.
getApiSpec()Retrieve openAPI file
Plumber$getApiSpec()
addEndpoint()addEndpoint has been deprecated in v0.4.0 and will be removed in a coming release. Please use handle() instead.
Plumber$addEndpoint( verbs, path, expr, serializer, processors, preempt = NULL, params = NULL, comments )
verbsverbs
pathpath
exprexpr
serializerserializer
processorsprocessors
preemptpreempt
paramsparams
commentscomments
addAssets()addAssets has been deprecated in v0.4.0 and will be removed in a coming release. Please use mount and PlumberStatic$new() instead.
Plumber$addAssets(dir, path = "/public", options = list())
dirdir
pathpath
optionsoptions
addFilter()$addFilter() has been deprecated in v0.4.0 and will be removed in a coming release. Please use $filter() instead.
Plumber$addFilter(name, expr, serializer, processors)
namename
exprexpr
serializerserializer
processorsprocessors
addGlobalProcessor()$addGlobalProcessor() has been deprecated in v0.4.0 and will be removed in a coming release. Please use $registerHook(s) instead.
Plumber$addGlobalProcessor(proc)
procproc
openAPIFile()Deprecated. Retrieve openAPI file
Plumber$openAPIFile()
swaggerFile()Deprecated. Retrieve openAPI file
Plumber$swaggerFile()
clone()The objects of this class are cloneable with this method.
Plumber$clone(deep = FALSE)
deepWhether to make a deep clone.
Routers are the core request handler in plumber. A router is responsible for taking an incoming request, submitting it through the appropriate filters and eventually to a corresponding endpoint, if one is found.
See https://www.rplumber.io/articles/programmatic-usage.html for additional details on the methods available on this object.
pr(),
pr_run(),
pr_get(), pr_post(),
pr_mount(),
pr_hook(), pr_hooks(), pr_cookie(),
pr_filter(),
pr_set_api_spec(), pr_set_docs(),
pr_set_serializer(), pr_set_parsers(),
pr_set_404(), pr_set_error(),
pr_set_debug(),
pr_set_docs_callback()
# NOT RUN {
## ------------------------------------------------
## Method `Plumber$mount`
## ------------------------------------------------
# }
# NOT RUN {
root <- pr()
users <- Plumber$new("users.R")
root$mount("/users", users)
products <- Plumber$new("products.R")
root$mount("/products", products)
# }
# NOT RUN {
## ------------------------------------------------
## Method `Plumber$registerHook`
## ------------------------------------------------
# }
# NOT RUN {
pr <- pr()
pr$registerHook("preroute", function(req){
cat("Routing a request for", req$PATH_INFO, "...\n")
})
pr$registerHooks(list(
preserialize=function(req, value){
print("About to serialize this value:")
print(value)
# Must return the value since we took one in. Here we're not choosing
# to mutate it, but we could.
value
},
postserialize=function(res){
print("We serialized the value as:")
print(res$body)
}
))
pr$handle("GET", "/", function(){ 123 })
# }
# NOT RUN {
## ------------------------------------------------
## Method `Plumber$handle`
## ------------------------------------------------
# }
# NOT RUN {
pr <- pr()
pr$handle("GET", "/", function(){
"<html><h1>Programmatic Plumber!</h1></html>"
}, serializer=plumber::serializer_html())
# }
# NOT RUN {
## ------------------------------------------------
## Method `Plumber$setSerializer`
## ------------------------------------------------
# }
# NOT RUN {
pr <- pr()
pr$setSerializer(serializer_unboxed_json())
# }
# NOT RUN {
## ------------------------------------------------
## Method `Plumber$set404Handler`
## ------------------------------------------------
# }
# NOT RUN {
pr <- pr()
pr$set404Handler(function(req, res) {cat(req$PATH_INFO)})
# }
# NOT RUN {
## ------------------------------------------------
## Method `Plumber$setErrorHandler`
## ------------------------------------------------
# }
# NOT RUN {
pr <- pr()
pr$setErrorHandler(function(req, res, err) {
message("Found error: ")
str(err)
})
# }
Run the code above in your browser using DataLab