Using nested map params with HTTPoison

Hello, I’m trying to integrate with an API that expects a json payload in the following format:

...
"foobar": [
    {
      "roles": "admin",
      "email": "foo@example.com"
    }
  ]

But I’m having a hard time trying to get this payload to work, as the nested map I was using originally is not able to be encoded via URI.encode_query.

I am now trying to do some URL-esque formatting in the params map, but it’s not quite decoding correctly. For example, this:

params = %{"foobar[roles]" => "admin", "foobar[email]" => "foo@bar.com"}
HTTPoison.post("http://localhost:4000/api", "", headers, [params: params])

Which is decoded on the server as (missing the wrapping []).

...
"foobar" => %{"roles" => "admin", "email" => "foo@example.com"}

I am working with HTTPoison, but am open to another library if it’s easier to use one.

Hey @BillBryson so I think the issue here is that you aren’t sending these as encoded JSON, you’re sending these as URI style queries for some reason. I think what you want is:

body = Jason.encode!(%{
  foobar: [%{roles: "admin", email: "foo@example.com"}]
})

headers = [{"content-type", "application/json"}] ++ headers

HTTPoison.post("http://localhost:4000/api", body, headers)

Basically, set a content type header to say that you’re sending json, and then encode your map / list elixir structure into json with the Jason library.

2 Likes

This was it. Thank you for taking the time to respond, I appreciate it.

2 Likes