fael.gabriel

fael.gabriel

Need to create a body for Tesla with duplicate map keys

Hey all,
I am using Tesla to make a POST request and I need to post a body with duplicate keys, like this map:

%{
  "id[]" => "1",
  "id[]" => "2",
  "id[]" => "3"
}

The problem is that when I try to create this map, it does not keep the duplicated keys id[], so how can I generate this kind of body with a list of duplicated keys?

What I have so far:
I have this map as input:

ids = %{
  "1" => "any-value",
  "2" => "any-value",
  "3" => "any-value"
}

and I am trying to convert that to this output to post as the body in Tesla:

%{
  "id[]" => "1",
  "id[]" => "2",
  "id[]" => "3"
}

with this code:

ids |> Enum.map(fn {id, _} -> %{"id[]" => id} end) |> Enum.reduce(&Map.merge/2)

but as I said this keeps only one id[] in the map, e.g: %{"id[]" => "1"}.

Does anyone have any thoughts on how can I achieve this?

Thanks in advance,
Rafael.

Most Liked

chulkilee

chulkilee

What’s the format of the body? Seems like you want application/x-www-form-urlencoded, so time to use Tesla.Middleware.FormUrlencoded, which uses URI.encode_query/1 under the hood.

    client = Tesla.client([
      {Tesla.Middleware.BaseUrl, "https://httpbin.org/"},
      Tesla.Middleware.EncodeFormUrlencoded,
      Tesla.Middleware.DecodeJson,
      Tesla.Middleware.Logger
    ])
    
    client |> Tesla.post("/post", [{"id[]", "1"},{"id[]", "2"}])

Output excerpt:

>>> REQUEST >>>
(no query)
content-type: application/x-www-form-urlencoded

id%5B%5D=1&id%5B%5D=2

<<< RESPONSE <<<

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "id[]": [
      "1",
      "2"
    ]
  },
  "headers": {
    "Content-Length": "21",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
  },
  "json": null,
  "url": "https://httpbin.org/post"
}

Please note

  • [] notation to take values into array is not a standard but just common convention. e.g. See Plug.Conn.Query
  • Elixir’s URI.decode_query returns a map, which is convenient but it’s wrong to use parse a string in urlencoded form, since WHATWG defines it as list of key/value, not map!

For that exact reason I wrote whatwg/www_form_urlencoded.ex at main · chulkilee/whatwg · GitHub a while ago.

Where Next?

Popular in Questions Top

logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
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

We're in Beta

About us Mission Statement