Passing JSON data directly to an API

I am trying to create API that can take in JSON data .

For example

#* Return the sum of two numbers
#* @post /sum
function(a, b) {
    as.numeric(a) + as.numeric(b)
} 

The above API for single value (http://host:port/sum?a=3&b=2 ) and below for JSON

#* Return the sum of two numbers given JSON input
#* 
#* @post /sum/json
function(req,res) {
  
  req$data <- tryCatch(jsonlite::fromJSON(req$postBody),
                               error = function(e) NULL)
  ....

   req$sum_values <- sum(req$data)
}


sum<- function(df){
  as.numeric(df$a) + as.numeric(df$b)
}

Input

[
 {
   "a": 5,
   "b": 3
 },
  {
   "a": 2,
   "b": 6
 }
]

Is it possible to use the dataframe alone directly in both cases with standard filters/serializers/de-serializers etc.

sum<- function(df){
  as.numeric(df$a) + as.numeric(df$b)
}

Note : My attempt is be least intrusive into a given model/function (Example :sum<- function(df) ) and do the maximum with decorators or standards.

Thanks

Using plumber github version

#* Return the sum of two numbers given JSON input
#* @param df:list
#* @post /sum/json
function(df) {
sum(unlist(df))
#or something else depending on how you structure your list/data.frame
}

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

Note that the json should have a df top-level properties for argument matching to work.

{"df":[
{
"a": 5,
"b": 3
},
{
"a": 2,
"b": 6
}
]}