6

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.

4

2 Answers 2

11

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.

2
  • Thanks, this is exactly what I needed.
    – Matt
    Dec 9, 2015 at 15:30
  • How to match for body_params values in controller action definitions?
    – W.M.
    Dec 12, 2017 at 12:46
7

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.