Learn R Programming

RestRserve (version 0.2.0.2)

Application: 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.

Arguments

Format

R6::R6Class object.

Construction

Constructor for Application.

Application$new(middleware = list(), content_type = "text/plain", ...)
  • middleware :: list of Middleware List of middlewares.

  • content_type :: character(1) Default response body content (media) type. "text/plain" by default.

  • ... Not used at the moment

Fields

  • logger :: Logger Logger object which records events during request processing. Alternatively user can use loggers from lgr package as a drop-in replacement - Logger methods and loggers created by lgr share function signatures.

  • content_type :: character(1) Default response body content type.

  • HTTPError :: HTTPError Class 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.

  • endpoints :: named list() Prints all the registered routes with allowed methods.

Methods

  • add_route(path, method, FUN, match = c("exact", "partial", "regex"), ...) character(1), character(1), character(1) -> invisible(self) - Application Adds endpoint and register user-supplied R function as a handler.

    Allowed methods at the moment: GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH.

    match parameter defines how route will be processed.

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

User function FUN must take two arguments: first is request (Request) and second is response (Response).

The goal of the user function is to modify response or throw exception (call raise() or stop()).

Both response and request objects modified in-place and internally passed further to RestRserve execution pipeline.

  • add_get(path, FUN, match = c("exact", "partial", "regex"), ..., add_head = TRUE) character(1), character(1), character(1), any, logical(1) -> invisible(self) - Application Shorthand to add_route with GET method. With add_head = TRUE HEAD method handlers will be added (with add_head()).

  • add_post(path, FUN, match = c("exact", "partial", "regex"), ...) character(1), character(1), character(1), any -> invisible(self) - Application Shorthand to add_route with POST method.

  • add_static(path, file_path, content_type = NULL, ...) character(1), character(1), character(1), any -> invisible(self) - Application Adds GET method to serve file or directory at file_path.

    If content_type = NULL then MIME code content_type will be inferred automatically (from file extension).

    If it will be impossible to guess about file type then content_type will be set to "application/octet-stream".

  • append_middleware(mw) Middleware -> invisible(self) - Application Appends middleware to handlers pipeline.

  • process_request(request) Request -> Response Process incoming request and generate Response object. Useful for tests your handlers before deploy application.

  • add_openapi(path = "/openapi.yaml", file_path = "openapi.yaml") character(1), named list(), character(1) -> invisible(self) - Application Adds endpoint to serve OpenAPI description of available methods.

  • add_swagger_ui(path = "/swagger", path_openapi = "/openapi.yaml", use_cdn = TRUE, path_swagger_assets = "/__swagger__/", file_path = "swagger-ui.html") character(1), character(1), logical(1), character(1), character(1) -> invisible(self) - Application Adds endpoint to show Swagger UI.

  • See Also

    HTTPError Middleware Request Response

    Examples

    Run this code
    # NOT RUN {
    # 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()
    # }
    # NOT RUN {
    backend$start(app, 8080)
    # }
    # NOT RUN {
    # }
    

    Run the code above in your browser using DataLab