Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPOISON - insert body parameters in elixir

Tags:

http

elixir

I'm trying to do a http request

def getPage() do
    url = "http://myurl"
    body = '{
              "call": "MyCall",
              "app_key": "3347249693",
              "param": [
                  {
                      "page"          : 1,
                      "registres"     : 100,
                      "filter"        : "N"
                  }
              ]
             }'

    headers = [{"Content-type", "application/json"}]
    HTTPoison.post(url, body, headers, [])
end

this works for me well.

my question is - how can I insert variables in the body request. meaning:

 def getPage(key, page, registers, filter) do
    url = "http://myurl"
    body = '{
              "call": "MyCall",
              "app_key": key,
              "param": [
                  {
                      "page"          : page,
                      "registres"     : registers,
                      "filter"        : filter
                  }
              ]
             }'

    headers = [{"Content-type", "application/json"}]
    HTTPoison.post(url, body, headers, [])
end

when I run it I get

%HTTPoison.Response{body: "\nFatal error: Uncaught exception 'Exception' with message 'Invalid JSON object' in /myurl/www/myurl_app/api/lib/php-wsdl/class.phpwsdl.servers.php:...

any suggestions?

like image 511
dina Avatar asked May 23 '16 07:05

dina


2 Answers

You really should be using a JSON encoder like Poison for this.

url = "http://myurl"
body = Poison.encode!(%{
  "call": "MyCall",
  "app_key": key,
  "param": [
    %{
      "page": page,
      "registres": registers,
      "filter": filter
    }
  ]
})
headers = [{"Content-type", "application/json"}]
HTTPoison.post(url, body, headers, [])
like image 62
Dogbert Avatar answered Nov 20 '22 09:11

Dogbert


You need to interpolate the values:

body = '{
          "call": "MyCall",
          "app_key": "#{key}",
          "param": [
              {
                  "page"          : #{page},
                  "registres"     : "#{registres}",
                  "filter"        : "#{filter}"
              }
          ]
         }'

If you use a JSON library (Poison is a popular choice) Then you could do something like this to turn Elixir data structures into a JSON representation:

body = %{
          call: "MyCall",
          app_key: key,
          param: [
              {
                  page: page,
                  registres: registers,
                  filter: filter
              }
          ]
         } |> Poison.encode!()
like image 42
Gazler Avatar answered Nov 20 '22 09:11

Gazler