みずりゅの自由帳

主に参加したイベントやソフトウェア技術/開発について記録しています

smallexライブラリのJson.getと、HTTPoison.getを触ってみる

下記の記事で利用されていた「smallex」ライブラリの「Json.get」について簡単に調べてみた。

qiita.com


まず、こちらの記事によると「smallex」は小粒なライブラリ(ちょっとしたTips集)らしい。

qiita.com

その中で、「Json.get」はgetリクエストでJson APIをコールする関数のようだ。
処理の中で「HTTPoison」と「Poison」を利用している。

https://github.com/piacerex/smallex/blob/master/lib/json.ex

使い方を知るために、サンプルを作ってみる。
なお、Elixirのバージョンは1.9(Erlangは22)で実施する。
一連のコマンドはこちら。

$ mix new hello_sample
$ cd hello_sample
$ vim mix.exs      ... ライブラリの修正
$ mix deps.get
$ vim lib/hello_sample.ex      ... 動作確認のコード修正
$ iex -S mix

mix.exsの修正

mix.exs」の修正を行う。
Json.getを利用するためにsmallexの宣言、および対になる処理としてHTTPoisonとPoisonを利用する場合の宣言も追記する。
smallexは、内部でHTTPoisonとPoisonを利用しているので、今回は依存関係が発生して細かいバージョンの指定が必要。
(※2019.08.15時点では、Poison の最新バージョンは4.0.1。しかし、smallexではバージョン3系のものが指定される)

コード中、コメントで「追記」とした箇所が追記箇所。全部で四箇所である。
このうち、smallmixに関係して追記したのはdepsへの一箇所のみ。
残りの三箇所はHTTPoisonとPoisonに関係する箇所。

defmodule HelloSample.MixProject do
  use Mix.Project

  def project do
    [
      app: :hello_sample,
      version: "0.1.0",
      elixir: "~> 1.9",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger, :httpoison]      #<- :httpoisonを追記
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      {:httpoison, "~> 1.5"},            #<- httpoisonの宣言を追記
      {:poison, "~> 3.1"},                #<- poisonの宣言を追記
      {:smallex, "~> 0.2.3"}            #<- smallexの宣言を追記
    ]
  end
end

ちなみに、「extra_applications:」に追記した「:httpoison」によって「HTTPosion.start」は省略できるらしい。

hexdocs.pm

修正が終わったら、「mix deps.get」を実施。

余談:Poisonのバージョン指定が誤っていた時

smallexとPoisonを同時に利用する場合、smallex側の依存関係でPoisonはバージョン3.1を利用することになる。
Poisonのバージョン4.0を指定してmix deps.getすると、以下のようなエラーメッセージが表示された。

$mix deps.get
Resolving Hex dependencies...

Failed to use "poison" (versions 4.0.0 and 4.0.1) because
  smallex (version 0.2.3) requires ~> 3.1
  mix.exs specifies ~> 4.0.0

** (Mix) Hex dependency resolution failed, change the version requirements of your dependencies or unlock them (by using mix deps.update or mix deps.unlock). If you are unable to resolve the conflicts you can try overriding with {:dependency, "~> 1.0", override: true}
$

lib/hello_sample.ex の修正

動作確認用にコードも修正。

mix new した際に作られたスケルトンコード「lib/hello_sample.ex」に対して追記を行う。
出力については、Loggerを利用した。
「require Logger」でLoggerの利用を宣言。

「 HTTPoison.get 」と「Json.get」を使って、それぞれで「connpass api」を呼び出して応答結果を見てみる。

defmodule HelloSample do
  require Logger

  〜(略)〜

  def connpass_httpoison do
    # https://connpass.com/about/api/
    domain = "https://connpass.com"
    path = "/api/v1/event/?keyword=elixir&count=5"
    url =  domain <> path

    response = HTTPoison.get!(url)
    body =  Poison.decode!(response.body)
#    Logger.info("httpoison-body: #{inspect body}")

    titles = body["events"] |> Enum.map( fn(e) -> e["title"] end)
    Logger.info("httpoison-get: #{inspect titles}")
  end

  def connpass_jsonget do
    # https://connpass.com/about/api/
    domain = "https://connpass.com"
    path = "/api/v1/event/?keyword=elixir&count=5"

    response = Json.get(domain, path)
#    Logger.info("jsonget-body: #{inspect response}")

    titles = response["events"] |> Enum.map( fn(e) -> e["title"] end)
    Logger.info("jsonget-get: #{inspect titles}")
  end

end

connpassのAPIについてこちらを参照。

APIリファレンス - connpass

動作確認

「iex -S mix」でiexを起動。
起動後、「HelloSample.connpass_httpoison」と「HelloSample.connpass_jsonget」を実行する。

実行結果から、どちらも同じ結果になったのが確認できた。

$iex -S mix
Erlang/OTP 22 [erts-10.4.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Compiling 1 file (.ex)
Interactive Elixir (1.9.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> HelloSample.connpass_httpoison

23:37:59.443 [info]  httpoison-get: ["ElixirConfJP 2019 - be simple, fast & reliable", "IT初心者の為のもくもく会×交流会#17", "#ProLabo(プロラボ)渋谷もくもく会(#駆け出しエンジニア or 初心者歓迎)#9", "【第10回清流elixir勉強会】Elixirでのパフォーマンス測定(速度)について", "Fun Fun Functional (2) 関数型言語Lightning Talks!!"]
:ok
iex(2)> HelloSample.connpass_jsonget
:ok

23:38:14.782 [info]  jsonget-get: ["ElixirConfJP 2019 - be simple, fast & reliable", "IT初心者の為のもくもく会×交流会#17", "#ProLabo(プロラボ)渋谷もくもく会(#駆け出しエンジニア or 初心者歓迎)#9", "【第10回清流elixir勉強会】Elixirでのパフォーマンス測定(速度)について", "Fun Fun Functional (2) 関数型言語Lightning Talks!!"]
iex(3)>