LoginSignup
12
1

【時短?】Sigilでラクラク!?APIリクエスト

Last updated at Posted at 2023-12-14

Elixir Advent Calendar 2023 15日目に参加させていただきます。

TL; DR

目指せcurlの書きごこち :triumph:

iex(1)> Mix.install [{:websigil, "~> 0.1.0"}]
:ok

iex(2)> import Websigil
Websigil

iex(3)> ~g{https://httpbin.org/user-agent}
%{"user-agent" => "req/0.4.5"}

iex(4)> ~g{https://qiita.com/api/v2/users/Syuparn}
%{
  "description" => "見習いエンジニア、記憶をあきらめ記録に頼ります",
  "facebook_id" => "",
  "followees_count" => 12,
  "followers_count" => 18,
  "github_login_name" => "Syuparn",
  "id" => "Syuparn",
  "items_count" => 109,
  "linkedin_id" => "",
  "location" => "Kanagawa, Japan",
  "name" => "",
  "organization" => "",
  "permanent_id" => 239887,
  "profile_image_url" => "https://avatars3.githubusercontent.com/u/36665200?v=4",
  "team_only" => false,
  "twitter_screen_name" => "syuparn",
  "website_url" => "https://volatile-notepad.netlify.app/"
}

はじめに

Sigilを使うことで、文字列リテラル等を手軽に作成できます。

# 式の埋め込み
iex(1)> ~c/2 + 7 = #{2 + 7}/
'2 + 7 = 9'
# 文字列リスト作成
iex(2)> ~w/i love elixir school/
["i", "love", "elixir", "school"]

このSigil、ユーザーが定義することも可能です。そこで今回は、URLを書くとレスポンスボディを返すSigilを作ってみました。

しくみ

中身はいたってシンプルです。Sigilは sigil_{文字}(string, []) という関数で定義できるため、sigil_g 内部でHTTPリクエスト(GET)を行っています1

lib/websigil.ex
defmodule Websigil do
  def sigil_g(string, []) do
    string
      |> URI.encode()
      |> Req.get!()
      |> Map.get(:body)
  end
end

エラーハンドリング等は一切考慮していないのでご了承ください :innocent:

おわりに

「プログラミングElixir」を読んだ時から頭の片隅にあったネタを放出できました。Sigil本体よりもhexの公開に時間がかかりました
他にも面白いことに使えそうなので、アイデアが出たら作ってみたいと思います。

参考記事

  1. 当初はwebの w にしようと思ったのですが、~w は既にあるので GETの g にしました。

12
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
1