This class encapsulates all of the logic of a plumber2 api, and is what gets
passed around in the functional api of plumber2. The Plumber2 class is a
subclass of the fiery::Fire class. Please consult the documentation for
this for additional information on what this type of server is capable of.
Note that the Plumber2 objects are reference objects, meaning that any
change to it will change all instances of the object.
Initialization
A new Plumber2-object is initialized using the new() method on the
generator:
api <- Plumber2$new() |
However, most users will use the functional api of the package and thus
construct one using api()
Super class
fiery::Fire -> Plumber2
Active bindings
request_routerThe router handling requests
header_routerThe router handling partial requests (the request will pass through this router prior to reading in the body)
doc_typeThe type of API documentation to generate. Can be either
"rapidoc"(the default),"redoc","swagger", orNULL(equating to not generating API docs)doc_pathThe URL path to serve the api documentation from
doc_argsFurther arguments to the documentation UI
Methods
Inherited methods
fiery::Fire$async()fiery::Fire$attach()fiery::Fire$close_ws_con()fiery::Fire$delay()fiery::Fire$exclude_static()fiery::Fire$extinguish()fiery::Fire$get_data()fiery::Fire$has_plugin()fiery::Fire$header()fiery::Fire$is_running()fiery::Fire$log()fiery::Fire$off()fiery::Fire$on()fiery::Fire$reignite()fiery::Fire$remove_async()fiery::Fire$remove_data()fiery::Fire$remove_delay()fiery::Fire$remove_time()fiery::Fire$resume()fiery::Fire$safe_call()fiery::Fire$send()fiery::Fire$serve_static()fiery::Fire$set_client_id_converter()fiery::Fire$set_data()fiery::Fire$set_logger()fiery::Fire$start()fiery::Fire$stop()fiery::Fire$test_header()fiery::Fire$test_message()fiery::Fire$test_request()fiery::Fire$test_websocket()fiery::Fire$time()fiery::Fire$trigger()
Method new()
Create a new Plumber2 api
Usage
Plumber2$new(
host = get_opts("host", "127.0.0.1"),
port = get_opts("port", 8080),
doc_type = get_opts("docType", "rapidoc"),
doc_path = get_opts("docPath", "__docs__"),
reject_missing_methods = get_opts("rejectMissingMethods", FALSE),
ignore_trailing_slash = get_opts("ignoreTrailingSlash", TRUE),
max_request_size = get_opts("maxRequestSize"),
shared_secret = get_opts("sharedSecret"),
compression_limit = get_opts("compressionLimit", 1000),
default_async = get_opts("async", "mirai"),
env = caller_env()
)Arguments
hostA string overriding the default host
portAn port number overriding the default port
doc_typeThe type of API documentation to generate. Can be either
"rapidoc"(the default),"redoc","swagger", orNULL(equating to not generating API docs)doc_pathThe URL path to serve the api documentation from
reject_missing_methodsShould requests to paths that doesn't have a handler for the specific method automatically be rejected with a 405 Method Not Allowed response with the correct Allow header informing the client of the implemented methods. Assigning a handler to
"any"for the same path at a later point will overwrite this functionality. Be aware that setting this toTRUEwill prevent the request from falling through to other routes that might have a matching method and path. This setting only affects handlers on the request router.ignore_trailing_slashLogical. Should the trailing slash of a path be ignored when adding handlers and handling requests. Setting this will not change the request or the path associated with but just ensure that both
path/to/resourceandpath/to/resource/ends up in the same handler. This setting will only affect routes that are created automatically.max_request_sizeSets a maximum size of request bodies. Setting this will add a handler to the header router that automatically rejects requests based on their
Content-Lengthheadershared_secretAssigns a shared secret to the api. Setting this will add a handler to the header router that automatically rejects requests if their
Plumber-Shared-Secretheader doesn't contain the same value. Be aware that this type of authentication is very weak. Never put the shared secret in plain text but rely on e.g. the keyring package for storage. Even so, if requests are send over HTTP (not HTTPS) then anyone can read the secret and use itcompression_limitThe size threshold in bytes for trying to compress the response body (it is still dependant on content negotiation)
default_asyncThe default evaluator to use for async request handling
envAn environment that will be used as the default execution environment for the API
Method format()
Human readable description of the api object
Method ignite()
Begin running the server. Will trigger the start event
Arguments
blockShould the console be blocked while running (alternative is to run in the background)
showcaseShould the default browser open up at the server address. If
TRUEthen a browser opens at the root of the api, unless the api contains OpenAPI documentation in which case it will open at that location. If a string the string is used as a path to add to the root before opening....Arguments passed on to the
starthandlersilentShould startup messaging by silenced
Method add_route()
Add a new route to either the request or header router
Arguments
nameThe name of the route to add. If a route is already present with this name then the provided route (if any) is merged into it
routeThe route to add. If
NULLa new empty route will be createdheaderLogical. Should the route be added to the header router?
afterThe location to place the new route on the stack.
NULLwill place it at the end. Will not have an effect if a route with the given name already exists.rootThe root path to serve this route from.
Method request_handler()
Add a handler to a request. See api_request_handlers for detailed information
Usage
Plumber2$request_handler(
method,
path,
handler,
serializers,
parsers = NULL,
use_strict_serializer = FALSE,
auth_flow = NULL,
auth_scope = NULL,
download = FALSE,
async = FALSE,
then = NULL,
doc = NULL,
route = NULL,
header = FALSE
)Arguments
methodThe HTTP method to attach the handler to
pathA string giving the path the handler responds to.
handlerA handler function to call when a request is matched to the path
serializersA named list of serializers that can be used to format the response before sending it back to the client. Which one is selected is based on the request
AcceptheaderparsersA named list of parsers that can be used to parse the request body before passing it in as the
bodyargument. Which one is selected is based on the requestContent-Typeheaderuse_strict_serializerBy default, if a serializer that respects the requests
Acceptheader cannot be found, then the first of the provided ones are used. Setting this toTRUEwill instead send back a406 Not Acceptableresponseauth_flowThe authentication flow the request must be validated by to be allowed into the handler, provided as a logical expression of authenticator names
auth_scopeThe scope required to access this handler given a successful authentication. Unless your authenticators provide scopes this should be
NULLdownloadShould the response mark itself for download instead of being shown inline? Setting this to
TRUEwill set theContent-Dispositionheader in the response toattachment. Setting it to a string is equivalent to setting it toTRUEbut will in addition also set the default filename of the download to the string valueasyncIf
FALSEcreate a regular handler. IfTRUE, use the default async evaluator to create an async handler. If a string, the async evaluator registered to that name is used. If a function is provided then this is used as the async evaluatorthenA function to call at the completion of an async handler
docOpenAPI documentation for the handler. Will be added to the
paths$<handler_path>$<handler_method>portion of the API.routeThe route this handler should be added to. Defaults to the last route in the stack. If the route does not exist it will be created as the last route in the stack.
headerLogical. Should the handler be added to the header router
Method message_handler()
Add a handler to a WebSocket message. See api_message for detailed information
Arguments
handlerA function conforming to the specifications laid out in
api_message()asyncIf
FALSEcreate a regular handler. IfTRUE, use the default async evaluator to create an async handler. If a string, the async evaluator registered to that name is used. If a function is provided then this is used as the async evaluatorthenA function to call at the completion of an async handler
Method redirect()
Add a redirect to the header router. Depending on the value
of permanent it will respond with a 307 Temporary Redirect or 308
Permanent Redirect. from and to can contain path parameters and
wildcards which will be matched between the two to construct the correct
redirect path.
Arguments
methodThe HTTP method the redirect should respond to
fromThe path the redirect should respond to
toThe path/URL to redirect the incoming request towards. After resolving any path parameters and wildcards it will be used in the
LocationheaderpermanentLogical. Is the redirect considered permanent or temporary? Determines the type of redirect status code to use
Method add_shiny()
Add a shiny app to an api. See api_shiny() for detailed
information
Arguments
pathThe path to serve the app from
appA shiny app object
exceptSubpaths to
paththat should not be forwarded to the shiny app. Be sure it doesn't contains paths that the shiny app needsauth_flowThe authentication flow the request must be validated by to be allowed into the handler, provided as a logical expression of authenticator names
auth_scopeThe scope required to access this handler given a successful authentication. Unless your authenticators provide scopes this should be
NULL
Method add_report()
Render and serve a Quarto or Rmarkdown document from an
endpoint. See api_report() for more information.
Usage
Plumber2$add_report(
path,
report,
...,
doc = NULL,
max_age = Inf,
async = TRUE,
finalize = NULL,
continue = FALSE,
cache_dir = tempfile(pattern = "plumber2_report"),
cache_by_id = FALSE,
auth_flow = NULL,
auth_scope = NULL,
route = NULL
)Arguments
pathThe base path to serve the report from. Additional endpoints will be created in addition to this.
reportThe path to the report to serve
...Further arguments to
quarto::quarto_render()orrmarkdown::render()docAn
openapi_operation()documentation for the report. Onlyqueryparameters will be used and a request body will be generated from this for the POST methods.max_ageThe maximum age in seconds to keep a rendered report before initiating a re-render
asyncShould rendering happen asynchronously (using mirai)
finalizeAn optional function to run before sending the response back. The function will receive the request as the first argument, the response as the second, and the server as the third.
continueA logical that defines whether the response is returned directly after rendering or should be made available to subsequent routes
cache_dirThe location of the render cache. By default a temporary folder is created for it.
cache_by_idShould caching be scoped by the user id. If the rendering is dependent on user-level access to different data this is necessary to avoid data leakage.
auth_flowThe authentication flow the request must be validated by to be allowed into the handler, provided as a logical expression of authenticator names
auth_scopeThe scope required to access this handler given a successful authentication. Unless your authenticators provide scopes this should be
NULLrouteThe route this handler should be added to. Defaults to the last route in the stack. If the route does not exist it will be created as the last route in the stack.
Method forward()
Add a reverse proxy from a path to a given URL. See
api_forward() for more details
Arguments
pathThe root to forward from
urlThe url to forward to
exceptSubpaths to
paththat should be exempt from forwardingauth_flowThe authentication flow the request must be validated by to be allowed into the handler, provided as a logical expression of authenticator names
auth_scopeThe scope required to access this handler given a successful authentication. Unless your authenticators provide scopes this should be
NULL
Method add_auth_guard()
Adds an auth guard to your API which can then be referenced in auth flows.
Arguments
guardAn Guard subclass object defining the scheme
nameThe name to use for referencing the scheme in an auth flow
Method add_auth()
Add an auth flow to an endpoint
Arguments
methodThe HTTP method to add auth to
pathA string giving the path to be authenticated
auth_flowA logical expression giving the auth flow the client must pass to get access to the resource
auth_scopeThe scope requirements of the resource
add_docShould OpenAPI documentation be added for the authentication