plumber R Package Documentation

repository·main·Indexed 23 days ago

https://github.com/rstudio/plumber

An R package for creating web APIs by decorating R functions with special comments. It transforms R code into HTTP endpoints using decorators like @get and @post, supports serving static files, and provides functions such as pr() and pr_run() to host the API server.

Tokens
525
Snippets
4
Records
4
Agent score
31%

What's inside plumber

  1. Install plumber

    main

    You can install the stable version from CRAN or the development version from GitHub.

    CRAN (Stable):

    install.packages("plumber")

    GitHub (Development):

    pak::pkg_install("rstudio/plumber")
    library(plumber)
    install.packages("plumber")
  2. Run a plumber API

    main

    To host your API, use the pr() function to load your decorated R script and pr_run() to start the server on a specified port.

    Example using a file named plumber.R:

    library(plumber)
    pr("plumber.R") %>%
      pr_run(port=8000)

    Once running, endpoints can be accessed via HTTP methods (GET, POST, etc.) using a browser, curl, or other HTTP clients.

    library(plumber)
    pr("plumber.R") %>%
      pr_run(port=8000)
  3. Serve static files with plumber

    main

    You can configure plumber to serve static files from a directory by defining specific paths. You can use the default path (typically /public) or define an explicit path (e.g., /static). Once configured, files located in your local directory (such as ./files) will be accessible via the corresponding URL paths.

    # Example access patterns:
    http://localhost:8000/static/b.txt
    http://localhost:8000/public/a.html
  4. Create a web API with plumber decorators

    main

    Plumber allows you to turn R functions into API endpoints by decorating them with roxygen2-like comments. Use the #* prefix for these decorators (rather than #' to avoid collisions with roxygen2).

    Common decorators include:

    • @get /path: Defines a GET endpoint.
    • @post /path: Defines a POST endpoint.
    • @param name description: Defines an input parameter.
    • @serializer type: Defines how the response is serialized (e.g., png, json).

    Request parameters (from query strings or POST bodies) are forwarded to the R function as arguments.

    #* Echo back the input
    #* @param msg The message to echo
    #* @get /echo
    function(msg="") {
      list(msg = paste0("The message is: '", msg, "'"))
    }