Plumber Router

plumb(file = NULL, dir = ".")

Arguments

file

The file to parse as the plumber router definition.

dir

The directory containing the plumber.R file to parse as the plumber router definition. Alternatively, if an entrypoint.R file is found, it will take precedence and be responsible for returning a runnable router.

Details

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 http://www.rplumber.io/articles/programmatic-usage.html for additional details on the methods available on this object.

Super class

plumber::hookable -> plumber

Active bindings

endpoints

plumber router endpoints read-only

filters

plumber router filters read-only

mounts

plumber router mounts read-only

environment

plumber router environment read-only

routes

plumber router routes read-only

Methods

Public methods

Inherited methods

Method new()

Create a new plumber router

Usage

plumber$new(file = NULL, filters = defaultPlumberFilters, envir)

Arguments

file

path to file to plumb

filters

a list of plumber filters

envir

an environment to be used as the enclosure for the routers execution

Returns

A new plumber router


Method run()

Start a server using plumber object.

Usage

plumber$run(
  host = "127.0.0.1",
  port = getOption("plumber.port"),
  swagger = interactive(),
  debug = interactive(),
  swaggerCallback = getOption("plumber.swagger.url", NULL)
)

Arguments

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.

swagger

a function that enhances the existing OpenAPI Specification.

debug

TRUE provides more insight into your API errors.

swaggerCallback

a callback function for taking action on the url for swagger page.

Details

port does not need to be explicitly assigned.

swagger should be either a logial or a function . When TRUE or a function, multiple handles will be added to plumber object. OpenAPI json file will be served on paths /openapi.json and /swagger.json. Swagger UI will be served on paths /__swagger__/index.html and /__swagger__/. When using a function, it will receive the plumber router as the first parameter and current OpenAPI Specification as the second. This function should return a list containing OpenAPI Specification. See http://spec.openapis.org/oas/v3.0.3

swaggerCallback When set, it will be called with a character string corresponding to the swagger UI url. It allows RStudio to open swagger UI when plumber router run method is executed using default plumber.swagger.url option.

Examples

\dontrun{
pr <- plumber$new
swagger <- function(pr_, spec) {
  spec$servers[[1]]$description <- "MyCustomAPISpec"
  spec
}
pr$run(swagger = swagger)
}


Method mount()

Mount a plumber router

Usage

plumber$mount(path, router)

Arguments

path

a character string. Where to mount router.

router

a plumber router. Router to be mounted.

Details

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.

Examples

\dontrun{
root <- plumber$new()

users <- plumber$new("users.R")
root$mount("/users", users)

products <- plumber$new("products.R")
root$mount("/products", products)
}


Method registerHook()

Register a hook

Usage

plumber$registerHook(
  stage = c("preroute", "postroute", "preserialize", "postserialize", "exit"),
  handler
)

Arguments

stage

a character string. Point in the lifecycle of a request.

handler

a hook function.

Details

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:

  1. preroute(data, req, res)

  2. postroute(data, req, res, value)

  3. preserialize(data, req, res, value)

  4. 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.

Examples

\dontrun{
pr <- plumber$new()
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

Usage

plumber$handle(methods, path, handler, preempt, serializer, endpoint, ...)

Arguments

methods

a character string. http method.

path

a character string. Api endpoints

handler

a handler function.

preempt

a preempt function.

serializer

a serializer function.

endpoint

a PlumberEndpoint object.

...

additional arguments for PlumberEndpoint creation

Details

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.

Examples

\dontrun{
pr <- plumber$new()
pr$handle("GET", "/", function(){
  "<html><h1>Programmatic Plumber!</h1></html>"
}, serializer=plumber::serializer_html())
}


Method print()

Print reprensation of plumber router.

Usage

plumber$print(prefix = "", topLevel = TRUE, ...)

Arguments

prefix

a character string. Prefix to append to representation.

topLevel

a logical value. When method executed on top level router, set to TRUE.

...

additional arguments for recursive calls

Returns

A terminal friendly represention of a plumber router.


Method serve()

Serve a request

Usage

plumber$serve(req, res)

Arguments

req

request object

res

response object


Method route()

Route a request

Usage

plumber$route(req, res)

Arguments

req

request object

res

response object


Method call()

httpuv interface call function

Usage

plumber$call(req)

Arguments

req

request object

Details

required for httpuv interface


Method onHeaders()

httpuv interface onHeaders function

Usage

plumber$onHeaders(req)

Arguments

req

request object

Details

required for httpuv interface


Method onWSOpen()

httpuv interface onWSOpen function

Usage

plumber$onWSOpen(ws)

Arguments

ws

WebSocket object

Details

required for httpuv interface


Method setSerializer()

Usage

plumber$setSerializer(serializer)

Arguments

serializer

a serializer function

Details

Sets the default serializer of the router.


Method set404Handler()

Usage

plumber$set404Handler(fun)

Arguments

fun

a handler function.

Details

Sets the handler that gets called if an incoming request can’t be served by any filter, endpoint, or sub-router.

Examples

\dontrun{
pr <- plumber$new()
pr$set404Handler(function(req, res) {cat(req$PATH_INFO)})
}


Method setErrorHandler()

Usage

plumber$setErrorHandler(fun)

Arguments

fun

a handler function.

Details

Sets the error handler which gets invoked if any filter or endpoint generates an error.

Examples

\dontrun{
pr <- plumber$new()
pr$setErrorHandler(function(req, res) {cat(res$body)})
}


Method filter()

Add a filter to plumber router

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 apiSpec()

Retrieve openAPI file

Usage

plumber$apiSpec()


Method openAPIFile()

Retrieve openAPI file

Usage

plumber$openAPIFile()


Method swaggerFile()

Retrieve openAPI file

Usage

plumber$swaggerFile()


Method addEndpoint()

Usage

plumber$addEndpoint(
  verbs,
  path,
  expr,
  serializer,
  processors,
  preempt = NULL,
  params = NULL,
  comments
)

Arguments

verbs

verbs

path

path

expr

expr

serializer

serializer

processors

processors

preempt

preempt

params

params

comments

comments

Details

addEndpoint has been deprecated in v0.4.0 and will be removed in a coming release. Please use handle() instead.


Method addAssets()

Usage

plumber$addAssets(dir, path = "/public", options = list())

Arguments

dir

dir

path

path

options

options

Details

addAssets has been deprecated in v0.4.0 and will be removed in a coming release. Please use mount and PlumberStatic$new() instead.


Method addFilter()

Usage

plumber$addFilter(name, expr, serializer, processors)

Arguments

name

name

expr

expr

serializer

serializer

processors

processors

Details

addFilter has been deprecated in v0.4.0 and will be removed in a coming release. Please use filter instead.


Method addGlobalProcessor()

Usage

plumber$addGlobalProcessor(proc)

Arguments

proc

proc

Details

addGlobalProcessor has been deprecated in v0.4.0 and will be removed in a coming release. Please use registerHook(s) instead.


Method clone()

The objects of this class are cloneable with this method.

Usage

plumber$clone(deep = FALSE)

Arguments

deep

Whether to make a deep clone.

Examples

## ------------------------------------------------ ## Method `plumber$run` ## ------------------------------------------------ if (FALSE) { pr <- plumber$new swagger <- function(pr_, spec) { spec$servers[[1]]$description <- "MyCustomAPISpec" spec } pr$run(swagger = swagger) } ## ------------------------------------------------ ## Method `plumber$mount` ## ------------------------------------------------ if (FALSE) { root <- plumber$new() users <- plumber$new("users.R") root$mount("/users", users) products <- plumber$new("products.R") root$mount("/products", products) } ## ------------------------------------------------ ## Method `plumber$registerHook` ## ------------------------------------------------ if (FALSE) { pr <- plumber$new() 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 `plumber$handle` ## ------------------------------------------------ if (FALSE) { pr <- plumber$new() pr$handle("GET", "/", function(){ "<html><h1>Programmatic Plumber!</h1></html>" }, serializer=plumber::serializer_html()) } ## ------------------------------------------------ ## Method `plumber$set404Handler` ## ------------------------------------------------ if (FALSE) { pr <- plumber$new() pr$set404Handler(function(req, res) {cat(req$PATH_INFO)}) } ## ------------------------------------------------ ## Method `plumber$setErrorHandler` ## ------------------------------------------------ if (FALSE) { pr <- plumber$new() pr$setErrorHandler(function(req, res) {cat(res$body)}) }