Handle json inbox with phoenix

I would like to handle incoming POST with application/json content type. I am just trying to return the published JSON as an answer to the test as follows:

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 mail is of the application/json content type, then the body is empty. If the content type is text or text/plain , then the body has content.

What is the correct way to parse the incoming body of an application/json request?

I am using Phoenix 1.2

+5
source share
1 answer

When the application/json request Content-Type, Plug analyzes the request body, and Phoenix passes it as params to the controller action, so params should contain what you want and you do not need to read the body and decrypt 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"}} 
+8
source

Source: https://habr.com/ru/post/1262082/


All Articles