Eric
Eric

Reputation: 1701

R plumber not parsing json arguments

According to the plumber docs, I should be able to pass function arguments in JSON format. Given the following server:

#* Return the sum of two numbers
#* @param a The first number to add
#* @param b The second number to add
#* @post /sum
function(a, b) {
  as.numeric(a) + as.numeric(b)
}

If I then start the server:

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

This works as expected:

curl --data "a=4&b=3" "http://localhost:8000/sum"
[7]

But this does not work, although the docs linked above seem to state it should:

curl --data '{"a":4, "b":5}' http://localhost:8000/sum

The error I get is:

<simpleError in (function (a, b) {    as.numeric(a) + as.numeric(b)})(): argument "a" is missing, with no default>

Can anyone spot what I am doing wrong?

Here is my sessionInfo:

R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.6

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] plumber_1.0.0.9999

loaded via a namespace (and not attached):
 [1] compiler_4.0.2      magrittr_2.0.1      R6_2.5.0            later_1.1.0.1      
 [5] promises_1.1.1.9001 tools_4.0.2         swagger_3.33.1      yaml_2.2.1         
 [9] Rcpp_1.0.5          stringi_1.5.3       jsonlite_1.7.2      webutils_1.1       
[13] httpuv_1.5.4        lifecycle_0.2.0     rlang_0.4.9.9000   

Upvotes: 1

Views: 658

Answers (2)

Bruno Tremblay
Bruno Tremblay

Reputation: 776

https://github.com/rstudio/plumber/issues/691

The doc need an update for curl.

Upvotes: 0

r2evans
r2evans

Reputation: 160397

I think the plumber documentation has an error. It says:

You can also send your data as JSON:

$ curl --data '{"a":4, "b":5}' http://localhost:8000/sum`

But what I think it should read is:

$ curl -H "Content-Type: application/json" --data '{"a":4, "b":5}' http://localhost:8000/sum`

In your case, you should also make sure to add -X POST, since you use #* @post /sum.

Try this on your (not-R) command line:

curl -X POST -H "Content-Type: application/json" --data '{"a":4, "b":5}' http://localhost:8000/sum

Explanation:

The reason it errs with Error: argument "a" is missing, with no default is because the input parser is normally looking for a pattern of "a=4&b=3". Notably, name=value, and among other things, there is no = in the json content on which it might be able to find things.

(In my opinion, I think strict enforcement of the input format is good. It would be better if it were to log something saying "unparseable content-type", but that's a different gripe.)

Upvotes: 1

Related Questions