Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix: Handle POST request body with Content-Type: application/json

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

like image 707
kind_robot Avatar asked Dec 30 '16 14:12

kind_robot


1 Answers

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"}}
like image 109
Dogbert Avatar answered Oct 28 '22 07:10

Dogbert