rplumber

R Plumber API - programmatically specify JSON schema for request


I'm trying to build a plumber API in R. Have started with this example from the docs...

pr() %>%
  pr_post("/echo", function(req, res) {
    if (is.null(req$body)) return("No input")
    list(
      input = req$body
    )
  }) %>%
  pr_run(port = 8080)

API starts OK. However, I want my handler function to use JSON in the body of the request as inputs.

Is it possible to programmatically define a JSON schema such that it's populated as the example in the swagger docs for the API?

Thanks.


Solution

  • Looks like this post Plumber: getting request body/schema in UI has the solution.

    This is (unless anyone can tell me it's bad practice) the example I was looking for...

    v <- data.frame(a = c(2, 3), 
                    b = c(3, 4))
    
    pr() %>%
      pr_post("/add_up", function(input = v) {
        input <- input[[1]]
        return(list(rowSums(input)))
      }) %>%
      pr_run(port = 8080) 
    

    This gives the following example JSON in the swagger docs...

    {
      "input": [
        [
          {
            "a": 2,
            "b": 3
          },
          {
            "a": 3,
            "b": 4
          }
        ]
      ]
    }
    

    ...and returns the following response...

    [
      [
        5,
        7
      ]
    ]
    

    Can anyone offer any improvement? Might be nice to remove the 'input' from the JSON schema if possible.