FvD FvD - 4 months ago 12
JSON Question

Have an R Plumber API consume JSON on POST

I'm writing and API in R using plumber that ideally will consume the JSON it receives on POST. But I cannot get the endpoint POST example to work that way, so I'm probably missing something obvious.

Using the example URL and Curl I can do the following without issue:

curl -i -X POST http://plumber.tres.tl/append/append -d "val=50"

But the way the example is presented:

POST {val: 50} -> http://plumber.tres.tl/append/append

Suggests that JSON would also be allowed. So I have tried:

curl -H "Content-Type: application/json" -X POST -d '{"val":50}' http://plumber.tres.tl/append/append

And all the variation to ensure UTF-8 encoding, comment out the
and all kinds of other combinations based mostly on what I found here on Stackoverflow about post. For example:

curl -i -X POST -H "Content-Type: application/json" http://plumber.tres.tl/append/append -d '{"val":50}'
curl -i -X POST -H "Accept: application/json" -H "Content-Type: application/json" http://plumber.tres.tl/append/append -d '{\"val\":50}'
curl -i -X POST -H "Content-Type: application/json;charset=UTF-8" http://plumber.tres.tl/append/append -d '{"val":50}'

Also using a file and trying to post it as
did not work.

Maybe it is something on the
side: I would expect that given the toolset to serialize the output, I can also state the expected serialization of the input. But I have not found how to do that.


This turned out to be a relatively simple issue with plumber. The function postBodyFilter calls parseQS that in turn splits on & and = and does not yet check for JSON formats (for example based on an initial { and ending }).

Since jsonlite was already imported by the package I proposed a small change to add basic JSON support in pull request #53.

Following the example in the README, the following will work after adding this patch:

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

Since the call is on jsonlite to parse the content of the querystring, more complex JSON should also be possible, but I have not tested that yet.

Update : This has now been merged into the plumber project and will work for you if you install the version from github using devtools::install_github("trestletech/plumber"), or through a traditional install as soon as version 0.3.1 is available on CRAN.