Custom swagger JSON for plumber APIs

We are developing a series of plumber APIs for RStudio Connect and would like to generate our own swagger.json file rather than rely on the one that is autogenerated by plumber. Is this possible and if so is there documentation on how to publish a custom swagger.json file to Connect?

Welcome to RStudio Community @poolio! There is a way to customize the swagger.json file in the development version of Plumber (see https://github.com/rstudio/plumber/pull/365). However, this does not currently work on RStudio Connect. The reason for this is because the swagger function is an argument to the $run() method of a Plumber router and RStudio Connect injects its own arguments to the $run() method for Plumber APIs. This is a known issue that we are working on.

Here is an example of supplying a custom swagger file to Plumber. Again, this will not work with RStudio Connect. Note that the directory for this example has the following structure:

.
├── api-spec.yaml
├── entrypoint.R
└── plumber.R
# api-spec.yaml
openapi: 3.0.0
servers:
  - description: Localhost
    url: http://127.0.0.1:5762
info:
  description: This is a simple Plumber API with the spec defined in an external file
  version: "1.0.0"
  title: Simple Plumber

paths:
  /echo:
    get:
      summary: Echos back a message
      description: |
        Pass a message and have it echoed in return in JSON
      parameters:
        - in: query
          name: msg
          description: Message to echo in return
          required: true
          schema:
            type: string
      responses:
        '200':
          description: successful message
# plumber.R
library(plumber)

#* @get /echo
function(msg = "") {
  list(msg = paste0("The message is: '", msg, "'"))
}
# entrypoint.R
library(plumber)

pr <- plumb("plumber.R")

pr$run(swagger = function(pr, spec, ...) {
  spec <- yaml::read_yaml("api-spec.yaml")
  spec
})
3 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

The latest release of Plumber (1.0.0) changes how this is done and makes it possible to customize the OpenAPI spec when deploying Plumber to RStudio Connect. See the Plumber docs for more information.

2 Likes