Matt
Matt

Reputation: 88067

How do I get the request body from a connection?

In the update(conn, params) action of my controller, how do I get out the JSON body passed in by the PUT request?

I see the values as a map in params, but with an "id" inserted into it. And if I pass an "id" it gets overwritten. The original body is probably somewhere in conn, but I don't know how you get to it.

Upvotes: 6

Views: 9167

Answers (2)

Gowiem
Gowiem

Reputation: 1408

If folks come to this when using Plug, you're looking to use Plug.Parsers.

Specifically you can do the following in your router file:

  plug Plug.Parsers, parsers: [:json],
                     pass:  ["text/*"],
                     json_decoder: Poison
  plug :match
  plug :dispatch

  # ...

  post "/" do
    IO.puts inspect conn.body_params
  end

Upvotes: 7

Gazler
Gazler

Reputation: 84150

You can use body_params on the Plug.Conn struct.

e.g.

#PUT /users/1
{"user": {"name": "lol"}, "id": 7}
  • params["id"] will be "1"
  • body_params["id"] will be 7

Hope this works for you.

Since you can only read_body/2 once, accessing the request body is a little more involved. You will need to bypass Plug.Parsers in your Endpoint for your requests and read the body manually.

From the Plug docs:

If you need to access the body multiple times, it is your responsibility to store it. Finally keep in mind some plugs like Plug.Parsers may read the body, so the body may be unavailable after accessing such plugs.

Upvotes: 11

Related Questions