DEV Community

SunnahSource
SunnahSource

Posted on

Build a Zakat & Nisab Calculator CLI in Elixir with Zero Dependencies (built-in JSON, :httpc, ETag cache)

Since Elixir 1.18 (on Erlang/OTP 27) you get a built-in JSON module, and OTP has always shipped an HTTP client (:httpc) and TLS (:ssl). That means a small, useful command-line tool can run as a single .exs script with no Mix project and no Hex packages.

In this tutorial we build a Zakat & Nisab calculator on top of the public sample from the SunnahSource Zakat API:

https://sunnahsource.org/data/json/zakat.json
Enter fullscreen mode Exit fullscreen mode

The tool will:

  • download the nisab values and the zakat rate from the API (no hard-coded numbers),
  • revalidate its local copy with ETag / If-None-Match (HTTP 304) and work --offline,
  • value the nisab with today's gold or silver price that you pass in,
  • print the API's guideline text in 9 languages (with English fallback),
  • output JSON for other programs, and
  • come with ExUnit tests.

1. What the API returns

Here is the shape of zakat.json (trimmed; translations shortened to two of the 9 languages):

{
  "title": "Zakat Calculator",
  "description": "Nisab values and zakat calculation guidelines",
  "is_free": false,
  "zakat_rate": 2.5,
  "nisab": [
    {"type": "gold", "unit": "grams", "value": 87.48, "tola": 7.5,
     "translations": {"en": "Gold nisab: 87.48 grams (7.5 tola). Zakat 2.5% on wealth held one lunar year.",
                      "ur": "سونے کی نصاب: 87.48 گرام (7.5 تولہ)۔ ایک قمری سال تک رکھے گئے مال پر 2.5% زکوٰۃ۔"}},
    {"type": "silver", "unit": "grams", "value": 612.36, "tola": 52.5,
     "translations": {"en": "Silver nisab: 612.36 grams (52.5 tola).", "ur": "..."}}
  ],
  "items": [
    {"category": "cash",
     "translations": {"en": "Cash, savings, and bank deposits are zakatable at 2.5%.", "ur": "..."}}
  ]
}
Enter fullscreen mode Exit fullscreen mode

The translations objects use the keys en, ur, fr, de, tr, ms, ru, zh-CN, ja. The response also sends an ETag header, which we will use for cheap revalidation.

Note that the API gives the nisab in grams, not in money. Gold and silver prices change every day and differ by country, so the calculator asks you for today's price per gram in your own currency.

2. Requirements

  • Elixir 1.18+ compiled with Erlang/OTP 27+ (check with elixir --version). On Debian 13 apt install elixir is enough; on macOS brew install elixir.
  • That's it. No mix new, no deps.

3. The whole script: zakat.exs

The file has three small modules:

  • Zakat.Data downloads the JSON over verified TLS, stores the body and the ETag in ~/.cache/sunnahsource/, and sends If-None-Match next time. On 304 Not Modified or a network error it uses the cached copy.
  • Zakat.Calc holds pure functions (easy to test): find a nisab entry, pick a translation with fallback, and compute the result.
  • Zakat.CLI parses flags with OptionParser and prints a report or JSON.
# zakat.exs: Zakat & Nisab calculator CLI (Elixir 1.18+, OTP 27+, zero dependencies)
# Data: https://sunnahsource.org/data/json/zakat.json
defmodule Zakat.Data do
  @url ~c"https://sunnahsource.org/data/json/zakat.json"

  def cache_dir do
    System.get_env("ZAKAT_CACHE_DIR") || Path.join(System.user_home!(), ".cache/sunnahsource")
  end

  defp body_path, do: Path.join(cache_dir(), "zakat.json")
  defp etag_path, do: Path.join(cache_dir(), "zakat.etag")

  @doc "Returns {:ok, data, source} where source is :network | :not_modified | :cache"
  def load(opts \\ []) do
    if opts[:offline], do: from_cache(), else: fetch()
  end

  defp fetch do
    {:ok, _} = Application.ensure_all_started([:inets, :ssl])

    headers =
      case File.read(etag_path()) do
        {:ok, etag} when etag != "" -> [{~c"if-none-match", String.to_charlist(etag)}]
        _ -> []
      end

    ssl = [
      verify: :verify_peer,
      cacerts: :public_key.cacerts_get(),
      customize_hostname_check: [match_fun: :public_key.pkix_verify_hostname_match_fun(:https)]
    ]

    req = {@url, [{~c"user-agent", ~c"zakat-exs/1.0"} | headers]}

    case :httpc.request(:get, req, [ssl: ssl, timeout: 15_000], body_format: :binary) do
      {:ok, {{_, 200, _}, resp_headers, body}} ->
        data = JSON.decode!(body)
        File.mkdir_p!(cache_dir())
        File.write!(body_path(), body)
        etag = for({~c"etag", v} <- resp_headers, do: List.to_string(v)) |> List.first()
        if etag, do: File.write!(etag_path(), etag)
        {:ok, data, :network}

      {:ok, {{_, 304, _}, _, _}} ->
        with {:ok, data, _} <- from_cache(), do: {:ok, data, :not_modified}

      {:ok, {{_, status, _}, _, _}} ->
        fallback("HTTP #{status}")

      {:error, reason} ->
        fallback(inspect(reason))
    end
  end

  defp fallback(why) do
    IO.puts(:stderr, "network problem (#{why}), trying the local cache")
    from_cache()
  end

  defp from_cache do
    case File.read(body_path()) do
      {:ok, body} -> {:ok, JSON.decode!(body), :cache}
      {:error, _} -> {:error, "no cached copy yet, run once without --offline"}
    end
  end
end

defmodule Zakat.Calc do
  @doc "Find the nisab entry (\"gold\" or \"silver\") in the API data."
  def nisab(data, metal) do
    Enum.find(data["nisab"], &(&1["type"] == metal)) ||
      raise ArgumentError, "unknown nisab type #{inspect(metal)}"
  end

  @doc "Text for a node's translations map, falling back to English."
  def text(%{"translations" => t}, lang), do: t[lang] || t["en"]

  @doc """
  assets: %{cash:, gold_grams:, silver_grams:, other:}
  prices: %{gold:, silver:} (price per gram in your currency)
  basis:  "gold" | "silver"
  """
  def compute(data, assets, prices, basis) do
    rate = data["zakat_rate"]
    gold_value = assets.gold_grams * prices.gold
    silver_value = assets.silver_grams * prices.silver
    total = assets.cash + gold_value + silver_value + assets.other

    n = nisab(data, basis)
    threshold = n["value"] * Map.fetch!(prices, String.to_atom(basis))
    due? = total >= threshold

    %{
      basis: basis,
      nisab_grams: n["value"],
      nisab_tola: n["tola"],
      nisab_threshold: round2(threshold),
      gold_value: round2(gold_value),
      silver_value: round2(silver_value),
      total_wealth: round2(total),
      above_nisab: due?,
      rate_percent: rate,
      zakat_due: if(due?, do: round2(total * rate / 100), else: 0.0)
    }
  end

  defp round2(x), do: Float.round(x * 1.0, 2)
end

defmodule Zakat.CLI do
  @switches [
    cash: :float, gold_grams: :float, silver_grams: :float, other: :float,
    gold_price: :float, silver_price: :float, nisab: :string, lang: :string,
    offline: :boolean, json: :boolean, help: :boolean
  ]

  def main(argv) do
    {opts, _, invalid} = OptionParser.parse(argv, strict: @switches)
    if invalid != [], do: die("unknown option(s): #{inspect(invalid)}")
    if opts[:help] do
      usage()
      System.halt(0)
    end

    prices = %{gold: opts[:gold_price] || 0.0, silver: opts[:silver_price] || 0.0}
    basis = opts[:nisab] || "silver"
    if basis not in ["gold", "silver"], do: die("--nisab must be gold or silver")

    if Map.fetch!(prices, String.to_atom(basis)) <= 0,
      do: die("give today's --#{basis}-price per gram so the nisab can be valued")

    assets = %{
      cash: opts[:cash] || 0.0,
      gold_grams: opts[:gold_grams] || 0.0,
      silver_grams: opts[:silver_grams] || 0.0,
      other: opts[:other] || 0.0
    }

    data =
      case Zakat.Data.load(offline: opts[:offline]) do
        {:ok, data, source} ->
          IO.puts(:stderr, "data: #{source}")
          data

        {:error, msg} -> die(msg)
      end

    result = Zakat.Calc.compute(data, assets, prices, basis)

    if opts[:json] do
      IO.puts(JSON.encode!(result))
    else
      print(result, data, opts[:lang] || "en")
    end
  end

  defp print(r, data, lang) do
    IO.puts("""
    Nisab basis : #{r.basis} = #{r.nisab_grams} g (#{r.nisab_tola} tola)
    Threshold   : #{money(r.nisab_threshold)}
    Gold value  : #{money(r.gold_value)}
    Silver value: #{money(r.silver_value)}
    Total wealth: #{money(r.total_wealth)}
    Above nisab : #{if r.above_nisab, do: "yes", else: "no"}
    Zakat due   : #{money(r.zakat_due)} (#{r.rate_percent}%)
    """)

    IO.puts(Zakat.Calc.text(Zakat.Calc.nisab(data, r.basis), lang))
    Enum.each(data["items"], &IO.puts(Zakat.Calc.text(&1, lang)))
  end

  defp money(x), do: :erlang.float_to_binary(x * 1.0, decimals: 2)

  defp usage do
    IO.puts("""
    elixir zakat.exs --cash 5000 --gold-grams 20 --gold-price 80 --silver-price 1 \\
                     [--silver-grams 0] [--other 0] [--nisab silver|gold] [--lang ur] [--json] [--offline]
    """)
  end

  defp die(msg) do
    IO.puts(:stderr, "error: " <> msg)
    System.halt(1)
  end
end

unless System.get_env("ZAKAT_NO_MAIN"), do: Zakat.CLI.main(System.argv())
Enter fullscreen mode Exit fullscreen mode

A few details worth pointing out:

  • TLS is verified. :httpc does not verify certificates unless you ask. :public_key.cacerts_get/0 (OTP 25+) loads the operating system's CA store, and pkix_verify_hostname_match_fun(:https) handles wildcard certificates.
  • body_format: :binary makes :httpc return a binary instead of a charlist, which is what JSON.decode!/1 wants.
  • Charlists vs strings. :httpc is an Erlang API, so the URL and header names are charlists (~c"...").
  • The last line runs the CLI only when the script is executed directly. The test file sets ZAKAT_NO_MAIN before loading it.

4. Run it

# 5,000 cash + 20 g gold, gold at 80/g, silver at 1/g (use your local prices)
elixir zakat.exs --cash 5000 --gold-grams 20 --gold-price 80 --silver-price 1
Enter fullscreen mode Exit fullscreen mode
data: network
Nisab basis : silver = 612.36 g (52.5 tola)
Threshold   : 612.36
Gold value  : 1600.00
Silver value: 0.00
Total wealth: 6600.00
Above nisab : yes
Zakat due   : 165.00 (2.5%)

Silver nisab: 612.36 grams (52.5 tola).
Cash, savings, and bank deposits are zakatable at 2.5%.
Enter fullscreen mode Exit fullscreen mode

Run it again with the gold nisab and Urdu text. This time the server answers 304, so nothing is downloaded:

elixir zakat.exs --cash 5000 --gold-grams 20 --gold-price 80 --silver-price 1 --nisab gold --lang ur
Enter fullscreen mode Exit fullscreen mode
data: not_modified
Nisab basis : gold = 87.48 g (7.5 tola)
Threshold   : 6998.40
Gold value  : 1600.00
Silver value: 0.00
Total wealth: 6600.00
Above nisab : no
Zakat due   : 0.00 (2.5%)

سونے کی نصاب: 87.48 گرام (7.5 تولہ)۔ ایک قمری سال تک رکھے گئے مال پر 2.5% زکوٰۃ۔
نقد، بچت اور بینک ڈپازٹ پر 2.5% زکوٰۃ ہے۔
Enter fullscreen mode Exit fullscreen mode

The same wealth is above the silver nisab but below the gold nisab. That's why the tool makes the basis an explicit --nisab choice instead of hiding it.

Machine-readable output, without touching the network:

elixir zakat.exs --cash 5000 --gold-grams 20 --gold-price 80 --silver-price 1 --json --offline
Enter fullscreen mode Exit fullscreen mode
{"basis":"silver","gold_value":1.6e3,"silver_value":0.0,"nisab_grams":612.36,"nisab_tola":52.5,"nisab_threshold":612.36,"total_wealth":6.6e3,"above_nisab":true,"rate_percent":2.5,"zakat_due":165.0}
Enter fullscreen mode Exit fullscreen mode

(1.6e3 is how Erlang writes the shortest exact float; it is valid JSON and parses as 1600.)

Errors exit with status 1:

$ elixir zakat.exs --cash 10 --nisab gold
error: give today's --gold-price per gram so the nisab can be valued
Enter fullscreen mode Exit fullscreen mode

5. Tests with ExUnit: zakat_test.exs

ExUnit also ships with Elixir, so tests are just another script:

ExUnit.start()
System.put_env("ZAKAT_NO_MAIN", "1")
Code.require_file("zakat.exs", __DIR__)

defmodule ZakatTest do
  use ExUnit.Case, async: true

  # Trimmed copy of the real zakat.json shape
  @data %{
    "zakat_rate" => 2.5,
    "nisab" => [
      %{"type" => "gold", "value" => 87.48, "tola" => 7.5,
        "translations" => %{"en" => "Gold nisab", "ur" => "سونے کی نصاب"}},
      %{"type" => "silver", "value" => 612.36, "tola" => 52.5,
        "translations" => %{"en" => "Silver nisab"}}
    ],
    "items" => []
  }
  @assets %{cash: 5000.0, gold_grams: 20.0, silver_grams: 0.0, other: 0.0}
  @prices %{gold: 80.0, silver: 1.0}

  test "silver basis: above nisab, 2.5% due" do
    r = Zakat.Calc.compute(@data, @assets, @prices, "silver")
    assert r.nisab_threshold == 612.36
    assert r.total_wealth == 6600.0
    assert r.above_nisab
    assert r.zakat_due == 165.0
  end

  test "gold basis: below nisab, nothing due" do
    r = Zakat.Calc.compute(@data, @assets, @prices, "gold")
    assert r.nisab_threshold == 6998.4
    refute r.above_nisab
    assert r.zakat_due == 0.0
  end

  test "exactly at nisab counts as reaching it" do
    a = %{cash: 612.36, gold_grams: 0.0, silver_grams: 0.0, other: 0.0}
    assert Zakat.Calc.compute(@data, a, @prices, "silver").above_nisab
  end

  test "translation falls back to English" do
    gold = Zakat.Calc.nisab(@data, "gold")
    assert Zakat.Calc.text(gold, "ur") == "سونے کی نصاب"
    assert Zakat.Calc.text(gold, "xx") == "Gold nisab"
  end

  test "unknown nisab type raises" do
    assert_raise ArgumentError, fn -> Zakat.Calc.nisab(@data, "copper") end
  end
end
Enter fullscreen mode Exit fullscreen mode
$ elixir zakat_test.exs
.....
5 tests, 0 failures
Enter fullscreen mode Exit fullscreen mode

6. Ideas to extend it

  • Wrap Zakat.Calc.compute/4 in a Phoenix LiveView form, or a Plug endpoint that returns the JSON.
  • Use the Hijri Calendar API to remind users when their zakat year (haul) comes round.
  • Show a dua after payment using the Duas API, or prayer times next to it with the Prayer Times API.
  • Add more asset types (business stock, receivables) as extra --other inputs.

Notes

  • This is a programming tutorial, not a fatwa. Rules on which assets count, debts, and gold versus silver nisab differ between scholars, so show users the basis you used and let them ask a scholar they trust.
  • The public JSON is a sample and the Zakat API is a premium API. For full data and an API key, see the Zakat API page and pricing.
  • Please keep the cache and don't poll the endpoint in a loop.
  • More examples and the endpoint list: github.com/sunnahsourceofficial-droid/sunnahsource-islamic-api.
  • Building an Islamic app and need a custom API? See SunnahSource or send a custom request.

Top comments (0)