| Application {RestRserve} | R Documentation |
Creates application - RestRserve usage starts from here
Description
Creates Application object. Application provides an interface for building high-performance REST API by registering R functions as handlers http requests.
Details
There are several advanced options to control how HTTP headers are processed:
-
options("RestRserve.headers.server")controls response"Server"header -
options("RestRserve.headers.split")controls which header values split by comma during parsing. See https://en.wikipedia.org/wiki/List_of_HTTP_header_fields, https://stackoverflow.com/a/29550711/3048453
There is also an option to switch-off runtime types validation in
the Request/Response handlers. This might provide some performance gains,
but ultimately leads to less robust applications. Use at your own risk!
See options("RestRserve.runtime.asserts")
Public fields
loggerLogger object which records events during request processing. Alternatively user can use loggers from lgr package as a drop-in replacement -
Loggermethods and loggers created bylgrshare function signatures.content_typeDefault response body content type.
HTTPErrorClass which raises HTTP errors. Global HTTPError is used by default. In theory user can replace it with his own class (see
RestRserve:::HTTPErrorFactory). However we believe in the majority of the cases using HTTPError will be enough.
Active bindings
endpointsPrints all the registered routes with allowed methods.
Methods
Public methods
Method new()
Creates Application object.
Usage
Application$new( middleware = list(EncodeDecodeMiddleware$new()), content_type = "text/plain", ... )
Arguments
middlewareList of Middleware objects.
content_typeDefault response body content (media) type.
"text/plain"by default....Not used at the moment.
Method add_route()
Adds endpoint and register user-supplied R function as a handler.
Usage
Application$add_route(
path,
method,
FUN,
match = c("exact", "partial", "regex"),
...
)Arguments
pathEndpoint path.
methodHTTP method. Allowed methods at the moment:
GET,HEAD,POST,PUT,DELETE,OPTIONS,PATCH.FUNUser function to handle requests.
FUNmust take two arguments: first isrequest(Request) and second isresponse(Response).
The goal of the user function is to modifyresponseor throw exception (callraise()orstop()).
Bothresponseandrequestobjects modified in-place and internally passed further to RestRserve execution pipeline.matchDefines how route will be processed. Allowed values:
-
exact- match route as is. Returns 404 if route is not matched. -
partial- match route as prefix. Returns 404 if prefix are not matched. -
regex- match route as template. Returns 404 if template pattern not matched.
-
...Not used.
Method add_get()
Shorthand to Application$add_route() with GET method.
Usage
Application$add_get(
path,
FUN,
match = c("exact", "partial", "regex"),
...,
add_head = TRUE
)Arguments
pathEndpoint path.
FUNUser function to handle requests.
FUNmust take two arguments: first isrequest(Request) and second isresponse(Response).
The goal of the user function is to modifyresponseor throw exception (callraise()orstop()).
Bothresponseandrequestobjects modified in-place and internally passed further to RestRserve execution pipeline.matchDefines how route will be processed. Allowed values:
-
exact- match route as is. Returns 404 if route is not matched. -
partial- match route as prefix. Returns 404 if prefix are not matched. -
regex- match route as template. Returns 404 if template pattern not matched.
-
...Not used.
add_headAdds HEAD method.
Method add_post()
Shorthand to Application$add_route() with POST method.
Usage
Application$add_post(path, FUN, match = c("exact", "partial", "regex"), ...)Arguments
pathEndpoint path.
FUNUser function to handle requests.
FUNmust take two arguments: first isrequest(Request) and second isresponse(Response).
The goal of the user function is to modifyresponseor throw exception (callraise()orstop()).
Bothresponseandrequestobjects modified in-place and internally passed further to RestRserve execution pipeline.matchDefines how route will be processed. Allowed values:
-
exact- match route as is. Returns 404 if route is not matched. -
partial- match route as prefix. Returns 404 if prefix are not matched. -
regex- match route as template. Returns 404 if template pattern not matched.
-
...Not used.
Method add_static()
Adds GET method to serve file or directory at file_path.
Usage
Application$add_static(path, file_path, content_type = NULL, ...)
Arguments
pathEndpoint path.
file_pathPath file or directory.
content_typeMIME-type for the content.
Ifcontent_type = NULLthen MIME codecontent_typewill be inferred automatically (from file extension).
If it will be impossible to guess about file type thencontent_typewill be set toapplication/octet-stream....Not used.
Method add_openapi()
Adds endpoint to serve OpenAPI description of available methods.
Usage
Application$add_openapi(path = "/openapi.yaml", file_path = "openapi.yaml")
Arguments
pathpath Endpoint path.
file_pathPath to the OpenAPI specification file.
Method add_swagger_ui()
Adds endpoint to show Swagger UI.
Usage
Application$add_swagger_ui( path = "/swagger", path_openapi = "/openapi.yaml", use_cdn = TRUE, path_swagger_assets = "/__swagger__/", file_path = "swagger-ui.html" )
Arguments
pathpath Endpoint path.
path_openapiPath to the OpenAPI specification file.
use_cdnUse CDN to load Swagger UI libraries.
path_swagger_assetsSwagger UI asstes endpoint.
file_pathPath to Swagger UI HTML file.
Method append_middleware()
Appends middleware to handlers pipeline.
Usage
Application$append_middleware(mw)
Arguments
mwMiddleware object.
Method process_request()
Process incoming request and generate Response object.
Usage
Application$process_request(request = NULL)
Arguments
requestRequest object.
Useful for tests your handlers before deploy application.
Method print()
Prints application details.
Usage
Application$print()
Method clone()
The objects of this class are cloneable with this method.
Usage
Application$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
HTTPError Middleware Request Response
Examples
# init logger
app_logger = Logger$new()
# set log level for the middleware
app_logger$set_log_level("debug")
# set logger name
app_logger$set_name("MW Logger")
# init middleware to logging
mw = Middleware$new(
process_request = function(rq, rs) {
app_logger$info(sprintf("Incomming request (id %s): %s", rq$id, rq$path))
},
process_response = function(rq, rs) {
app_logger$info(sprintf("Outgoing response (id %s): %s", rq$id, rs$status))
},
id = "awesome-app-logger"
)
# init application
app = Application$new(middleware = list(mw))
# set internal log level
app$logger$set_log_level("error")
# define simply request handler
status_handler = function(rq, rs) {
rs$set_body("OK")
rs$set_content_type("text/plain")
rs$set_status_code(200L)
}
# add route
app$add_get("/status", status_handler, "exact")
# add static file handler
desc_file = system.file("DESCRIPTION", package = "RestRserve")
# add route
app$add_static("/desc", desc_file, "text/plain")
# define say message handler
say_handler = function(rq, rs) {
who = rq$parameters_path[["user"]]
msg = rq$parameters_query[["message"]]
if (is.null(msg)) msg = "Hello"
rs$set_body(paste(who, "say", dQuote(msg)))
rs$set_content_type("text/plain")
rs$set_status_code(200L)
}
# add route
app$add_get("/say/{user}", say_handler, "regex")
# print application info
app
# test app
# simulate requests
not_found_rq = Request$new(path = "/no")
status_rq = Request$new(path = "/status")
desc_rq = Request$new(path = "/desc")
say_rq = Request$new(path = "/say/anonym", parameters_query = list("message" = "Hola"))
# process prepared requests
app$process_request(not_found_rq)
app$process_request(status_rq)
app$process_request(desc_rq)
app$process_request(say_rq)
# run app
backend = BackendRserve$new()
if (interactive()) {
backend$start(app, 8080)
}