読者です 読者をやめる 読者になる 読者になる

HTTPoisonを試してみた

edgurgel/httpoison

README見ながら簡単に試してみただけなので上記URLでやってることとほぼ同じ。

ブログのテスト及び備忘録がてら書く。

mixプロジェクト作成

mix で作成

$ mix new github_api
* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/github_api.ex
* creating test
* creating test/test_helper.exs
* creating test/github_api_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd github_api
    mix test

Run "mix help" for more commands.

インストール

mix.exsにプラグインを記載

# mix.exs

def application do
  [applications: [:logger, :httpoison]]
end

defp deps do
  [
    {:poison, "~> 3.0"},
    {:httpoison, "~> 0.10.0"}
  ]
end

インストール

$ mix deps.get

書く

defmodule GithubApi do
  use HTTPoison.Base

  @expected_fields ~w(
    login id avater_url gravater_id url html_url followers_url
    following_url gists_url starred_url subscriptions_url
    organizations_url repos_url events_url received_events_url type
    site_domain name company blog location email hireable bio public_repos
    public_gists followers following created_at updated_at
  )

  def process_url(user_name) do
    "https://api.github.com/users/" <> user_name
  end

  def process_response_body(body) do
    body
    |> Poison.decode!
    |> Map.take(@expected_fields)
    |> Enum.map(fn({k, v}) -> {String.to_atom(k), v} end)
  end
end

使う

$ iex -S mix
iex> GithubApi.get!("jit-y").body
[bio: nil, blog: "http://qiita.com/jit-y", company: nil,
 created_at: "2016-08-19T15:21:22Z", email: nil,
 events_url: "https://api.github.com/users/jit-y/events{/privacy}",
 followers: 0, followers_url: "https://api.github.com/users/jit-y/followers",
 following: 0,
 following_url: "https://api.github.com/users/jit-y/following{/other_user}",
 gists_url: "https://api.github.com/users/jit-y/gists{/gist_id}", hireable: nil,
 html_url: "https://github.com/jit-y", id: 21127627, location: "Tokyo, Japan",
 login: "jit-y", name: "Yuji Takahashi",
 organizations_url: "https://api.github.com/users/jit-y/orgs", public_gists: 0,
 public_repos: 9,
 received_events_url: "https://api.github.com/users/jit-y/received_events",
 repos_url: "https://api.github.com/users/jit-y/repos",
 starred_url: "https://api.github.com/users/jit-y/starred{/owner}{/repo}",
 subscriptions_url: "https://api.github.com/users/jit-y/subscriptions",
 type: "User", updated_at: "2016-12-10T12:00:36Z",
 url: "https://api.github.com/users/jit-y"]

所感

  • あんまりelixirぽいことしてないけどとりあえずこんなカンジで
  • これからやりたいこと
    • phoenixいじる
      • なにかアプリ作る
        • Phoenix × Reactとかでできたらよいな
    • erlangをいじる
      • elixirいじってるとよくerlangのライブラリが出てくるので必須っぽい
      • すごいE本が有名なのでこれを読もうかな
        • web版のがあったのでまずはこれ読む