Fl4m3Ph03n1x

Fl4m3Ph03n1x

How to use Plug.Parsers?

Background

I have a Plug Router that has some simple endpoints. One of these endpoints is a put method that receives a JSON body. I want to use Plug.Parsers to decode the body before processing it but I am having errors and I don’t know why.

Code

This is my router. Requests come here to be dispatched:

defmodule Api do
  use Plug.Router

  plug :match
  plug Plug.Parsers, parsers: [:urlencoded, :json],
    json_decoder: Jason
  plug :dispatch

  put "/cars"    do
    IO.inspect conn
    Conn.send_resp(conn, Status.code(:ok), "OK")
  end

end

To exercise this code, I have the following test:

    test "returns 200 OK when the list of cars is loaded correctly" do
      # Arrange
      body_params = "[
        {
          \"id\": 1,
          \"number\": 4
        },
        {
          \"id\": 2,
          \"number\": 6
        }
      ]"

      conn =
        :put
        |> conn("/cars")
        |> put_req_header("accept", "application/json")
        |> put_req_header("content-type", "application/json")
        |> put_body_params(body_params)

      # Act
      conn = Api.call(conn, @opts)

      # Assert
      assert conn.state == :sent
      assert conn.status == 200
      assert conn.resp_body == "OK"
    end

According to my knowledge, this should work, but I get the following error:

test PUT /cars returns 200 OK when the list of cars is loaded correctly (ApiTest)
test/api_test.exs:69
** (BadMapError) expected a map, got: “[\n {\n "id": 1,\n "number": 4\n },\n {\n "id": 2,\n "number": 6\n }\n ]”
code: conn = Api.call(conn, @opts)
stacktrace:
(stdlib 3.10) :maps.merge(%{}, “[\n {\n "id": 1,\n "seats": 4\n },\n {\n "id": 2,\n "seats": 6\n }\n ]”)
(plug 1.10.4) lib/plug/parsers.ex:354: Plug.Parsers.merge_params/4
(plug 1.10.4) lib/plug/parsers.ex:299: Plug.Parsers.call/2
(api 0.1.0) lib/api.ex:1: Api.plug_builder_call/2
test/api_test.exs:91: (test)

Questions

  1. Is my configuration of the router incorrect?
  2. Will the parser be applied to all incoming requests?
  3. What happens if I get a request that is not JSON? (will the parser ignore it?)
  4. What am I doing wrong?

Marked As Solved

al2o3cr

al2o3cr

Using put_body_params entirely short-circuits the parsing in Plug.Parser - that only happens when body_params is a %Plug.Unfetched{}.

You want to set the body to the unparsed JSON when calling Plug.Test.conn/3:

conn(:put, "/cars", body_params_json_string)
|> put_request_header("content-type", "application/json")
|> put_request_header("accept", "application/json")

Where Next?

Popular in Questions Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 130286 1222
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36654 110
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement