6

I want to create a Github token in Elixir using HTTPoison library, but i just cant not figure out how to send HTTPoison the parameter.

When using curl, it will be something like this

$ curl -i -u "ColdFreak" -H "X-GitHub-OTP: 123456" -d '{"scopes": ["repo", "user"], "note"
: "getting-started"}' https://api.github.com/authorizations

when I use the HTTPoison library, I just cannot figure out how to post it .

url = "https://api.github.com/authorizations"
HTTPoison.post!(url, [scopes: ["repo", "user"], note: "getting-started"],  %{"X-GitHub-OTP" => "12345"})

then it gave the error something like this

** (ArgumentError) argument error
            :erlang.iolist_to_binary([{"scopes", ["repo", "user"]}, {"note", "getting-started"}])
  (hackney) src/hackney_client/hackney_request.erl:338: :hackney_request.handle_body/4
  (hackney) src/hackney_client/hackney_request.erl:79: :hackney_request.perform/2

Can someone tell me how to do it the right way

HTTPoison's documentation is here

scc
  • 10,342
  • 10
  • 51
  • 65
王志軍
  • 1,021
  • 1
  • 11
  • 21

1 Answers1

11

The problem is with your body HTTPoison expects either a binary or a tuple in the format {:form, [foo: "bar"]}:

HTTPoison.post!(url, {:form, [scopes: "repo, user", note: "getting-started"]},  %{"X-GitHub-OTP" => "610554"})

or

HTTPoison.post!(url, "{\"scopes\": \"repo, user\", \"note\": \"getting-started\"}",  %{"X-GitHub-OTP" => "610554"})

You can use the Poison library to generate the JSON above:

json = %{scopes: "repo, user", note: "getting-started"} |> Poison.encode!
HTTPoison.post!(url, json, %{"X-GitHub-OTP" => "610554"})
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • keywork `:form` is necessry, I didn't know that, thank you very much!!!! It works! I'll try `Poison` too, you really saved me a lot of time!! – 王志軍 Sep 10 '15 at 08:09