I'm wondering what the most idiomatic way is to use URI
to add a query string to a base URI in Elixir.
I'm currently doing something like this:
iex(1)> base = "http://example.com/endpoint"
"http://example.com/endpoint"
iex(2)> query_string = URI.encode_query(foo: "bar")
"foo=bar"
iex(3)> uri_string = URI.parse(base) |> Map.put(:query, query_string) |> URI.to_string
"http://example.com/endpoint?foo=bar"
But was wondering if there is a cleaner way to set the query string. I know about URI.merge/2
, but I don't think a query string is a valid URI, so that's probably not approriate here (the ?
will not be added).
I could also do something like:
uri_string = %URI{ URI.parse(base) | query: query_string } |> URI.to_string
But I'm wondering if there is a simpler or clearer method I've missed.
I think your first example, with some formatting, reads pretty well:
uri_string =
base_url
|> URI.parse()
|> Map.put(:query, URI.encode_query(params))
|> URI.to_string()
I'm not aware of other idioms/shortcuts.
I'm not sure that it's more idiomatic but you can do simple string interpolation if you know the string you're trying to build.
uri_string = "#{base}?#{query_string}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With