I'd like to handle an incoming POST with application/json
content type. I am simply trying to return posted JSON as response to test like this:
WebhookController controller
pipeline :api do
plug :accepts, ["json"]
end
def handle(conn, params) do
{:ok, body, conn} = Plug.Conn.read_body(conn)
json(conn, %{body: body})
end
router.ex
scope "/webhook", MyApp do
pipe_through :api
post "/handle", WebhookController, :handle
end
If the incoming post has content type application/json
, then body is empty. If the content type is text
or text/plain
, then body has the content.
What is the right way to parse incoming application/json
request body?
I am using Phoenix 1.2
When the Content-Type of the request is application/json
, Plug parses the request body and Phoenix passes it as params
to the controller action, so params
should contain what you want and you don't need to read the body and decode it yourself:
def handle(conn, params) do
json(conn, %{body: params})
end
$ curl -XPOST -H 'Content-Type: application/json' --data-binary '{"foo": "bar"}' http://localhost:4000/handle
{"body":{"foo":"bar"}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With