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 the Programmatic Usage article for additional details on the methods available on this object.
Examples
## ------------------------------------------------## 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)## End(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})## End(Not run)## ------------------------------------------------## Method `Plumber$handle`## ------------------------------------------------## Not run:pr <- pr()pr$handle("GET","/",function(){"<html><h1>Programmatic Plumber!</h1></html>"}, serializer=plumber::serializer_html())## End(Not run)## ------------------------------------------------## Method `Plumber$setSerializer`## ------------------------------------------------## Not run:pr <- pr()pr$setSerializer(serializer_unboxed_json())## End(Not run)## ------------------------------------------------## Method `Plumber$set404Handler`## ------------------------------------------------## Not run:pr <- pr()pr$set404Handler(function(req, res){cat(req$PATH_INFO)})## End(Not run)## ------------------------------------------------## Method `Plumber$setErrorHandler`## ------------------------------------------------## Not run:pr <- pr()pr$setErrorHandler(function(req, res, err){ message("Found error: ") str(err)})## End(Not run)
host: a 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.
port: a 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()`.
swagger: Deprecated. Please use docs instead. See $setDocs(docs) or $setApiSpec() for more customization.
debug: If TRUE, it will provide more insight into your API errors. Using this value will only last for the duration of the run. If a $setDebug() has not been called, debug will default to FALSE at $run() time. See $setDebug() for more details.
swaggerCallback: An optional single-argument function that is called back with the URL to an OpenAPI user interface when one becomes ready. If missing, defaults to information previously set with $setDocsCallback(). This value will only be used while running the router.
...: Should be empty.
docs: Visual documentation value to use while running the API. This value will only be used while running the router. If missing, defaults to information previously set with setDocs(). For more customization, see $setDocs() or pr_set_docs() for examples.
quiet: If TRUE, don't print routine startup messages.
Method mount()
Mount a Plumber router
Plumber routers can be “nested” 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.
path: a character string. Where to unmount router.
Method 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)
In all of the above you have access to a disposable environment in the 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.
stage: a character string. Point in the lifecycle of a request.
handler: a hook function.
Examples
\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 })
}
Method handle()
Define endpoints
The “handler” 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()
Sets the default parsers of the router. Initialized to c("json", "form", "text", "octet", "multi")
Usage
Plumber$setParsers(parsers)
Arguments
parsers: Can 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")
```
Method set404Handler()
Sets the handler that gets called if an incoming request can’t be served by any filter, endpoint, or sub-router.
docs: a 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.
...: Arguments for the visual documentation. See each visual documentation package for further details.
Method 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 locate visual documentation.
If using options_plumber(), the value must be set before initializing your Plumber router.
callback: a callback function for taking action on the docs url. (Also accepts NULL values to disable the callback.)
Method setDebug()
Set debug value to include error messages.
See also: $getDebug() and pr_set_debug()
Usage
Plumber$setDebug(debug = FALSE)
Arguments
debug: TRUE provides more insight into your API errors.
Method getDebug()
Retrieve the debug value. If it has never been set, it will return FALSE.
See also: $getDebug() and pr_set_debug()
Usage
Plumber$getDebug()
Method filter()
Add a filter to plumber router
See also: pr_filter()
Usage
Plumber$filter(name, expr, serializer)
Arguments
name: a character string. Name of filter
expr: an expr that resolve to a filter function or a filter function
serializer: a serializer function
Method setApiSpec()
Allows to modify router autogenerated OpenAPI Specification
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()
Usage
Plumber$setApiSpec(api = NULL)
Arguments
api: This 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.
* a path to an OpenAPI Specification
The value returned will not be validated for OAS compatibility.
Method getApiSpec()
Retrieve OpenAPI file
Usage
Plumber$getApiSpec()
Method addEndpoint()
addEndpoint has been deprecated in v0.4.0 and will be removed in a coming release. Please use handle() instead.