DEV Community

SunnahSource
SunnahSource

Posted on

Build a 99 Names of Allah (Asma ul Husna) Quiz CLI in Lua 5.4 with lua-cjson, a 24h Cache and 9 Languages

Lua is tiny, fast to start and already on a lot of machines (it is embedded in Neovim, Redis, nginx/OpenResty and many games). That makes it a nice fit for a quick command-line tool. In this tutorial we build a 99 Names of Allah (Asma ul Husna) CLI in Lua 5.4 that:

  • fetches the Asma ul Husna API from QuraniAPI (one JSON request, 9 languages in one response)
  • caches the response for 24 hours and works with --offline
  • falls back to stale cache if the network is down
  • lists, shows and searches names (transliteration, meaning or Arabic)
  • runs a multiple-choice meaning quiz in your language

The only dependencies are lua5.4, lua-cjson and curl.

1. The endpoint

GET https://quranicapi.online/api/serve.php?slug=asma-ul-husna&lang=all
Enter fullscreen mode Exit fullscreen mode

lang can be all or one of en ur fr de tr ms ru zh-CN ja. CORS is open, the response is plain JSON over HTTPS, and no key is needed for the public sample. Trimmed response:

{
  "title": "99 Names of Allah (Asma ul Husna)",
  "description": "The beautiful names of Allah with meanings in 9 languages",
  "is_free": false,
  "total": 99,
  "items": [
    {
      "number": 1,
      "arabic": "الرَّحْمَنُ",
      "transliteration": "Ar-Rahman",
      "translations": {
        "en": "The Entirely Merciful",
        "ur": "بڑا مہربان",
        "fr": "Le Tout Miséricordieux",
        "de": "Der Allerbarmer",
        "tr": "Rahman",
        "ms": "Maha Pemurah",
        "ru": "Милостивый",
        "zh-CN": "至仁",
        "ja": "慈悲深い"
      }
    }
  ],
  "note": "Showing 12 of 99 names. Full dataset available with premium subscription.",
  "success": true,
  "slug": "asma-ul-husna"
}
Enter fullscreen mode Exit fullscreen mode

Note the note field: the public sample returns 12 of the 99 names. The full set of 99 comes with a premium key (see pricing). Our code just reads items, so it works the same with the sample or the full dataset.

2. Install

Debian/Ubuntu:

sudo apt install lua5.4 lua-cjson curl
Enter fullscreen mode Exit fullscreen mode

macOS (Homebrew): brew install lua luarocks && luarocks install lua-cjson.

3. The code

Save this as asma.lua:

#!/usr/bin/env lua5.4
-- asma.lua: 99 Names of Allah (Asma ul Husna) CLI using the QuraniAPI JSON endpoint
local cjson = require("cjson.safe")

local API   = "https://quranicapi.online/api/serve.php?slug=asma-ul-husna&lang=all"
local LANGS = { en=true, ur=true, fr=true, de=true, tr=true, ms=true, ru=true, ["zh-CN"]=true, ja=true }
local TTL   = 24 * 60 * 60
local CACHE_DIR  = (os.getenv("XDG_CACHE_HOME") or (os.getenv("HOME") .. "/.cache")) .. "/asma-lua"
local CACHE_FILE = CACHE_DIR .. "/asma-ul-husna.json"

local function die(msg) io.stderr:write("error: " .. msg .. "\n"); os.exit(1) end

local function read_file(path)
  local f = io.open(path, "rb"); if not f then return nil end
  local s = f:read("a"); f:close(); return s
end

local function write_file(path, data)
  os.execute(string.format("mkdir -p %q", CACHE_DIR))
  local tmp = path .. ".tmp"
  local f = assert(io.open(tmp, "wb")); f:write(data); f:close()
  assert(os.rename(tmp, path))
end

local function file_age(path)
  local p = io.popen(string.format("stat -c %%Y %q 2>/dev/null", path))
  local m = tonumber(p:read("a")); p:close()
  return m and (os.time() - m) or math.huge
end

local function http_get(url)
  -- -f: fail on HTTP errors, -sS: quiet but show errors, --max-time: don't hang
  local p = io.popen(string.format("curl -fsS --max-time 15 -H 'Accept: application/json' %q", url))
  local body = p:read("a"); local ok = p:close()
  if not ok or body == "" then return nil end
  return body
end

local function load_data(offline)
  local cached = read_file(CACHE_FILE)
  if cached and (offline or file_age(CACHE_FILE) < TTL) then
    local d = cjson.decode(cached); if d then return d, "cache" end
  end
  if offline then die("no cached data yet; run once without --offline") end
  local body = http_get(API)
  local d = body and cjson.decode(body)
  if d and type(d.items) == "table" then
    write_file(CACHE_FILE, body); return d, "network"
  end
  if cached then -- network failed: fall back to stale cache
    local s = cjson.decode(cached); if s then return s, "stale cache" end
  end
  die("could not fetch " .. API)
end

local function meaning(item, lang)
  local t = item.translations or {}
  return t[lang] or t.en or item.translation or "?"
end

local function show(item, lang)
  print(string.format("%2d. %s  (%s)", item.number, item.arabic, item.transliteration))
  print("    " .. meaning(item, lang))
end

local function lower(s) return (s or ""):lower() end

local function search(items, q, lang)
  q = lower(q); local hits = 0
  for _, it in ipairs(items) do
    if lower(it.transliteration):find(q, 1, true)
       or lower(meaning(it, lang)):find(q, 1, true)
       or lower(meaning(it, "en")):find(q, 1, true)
       or (it.arabic or ""):find(q, 1, true) then
      show(it, lang); hits = hits + 1
    end
  end
  if hits == 0 then print("no match for '" .. q .. "'") end
end

local function shuffle(t)
  for i = #t, 2, -1 do local j = math.random(i); t[i], t[j] = t[j], t[i] end
  return t
end

local function quiz(items, lang, rounds)
  if #items < 4 then die("need at least 4 names for a quiz") end
  local score = 0
  for r = 1, rounds do
    local pool = shuffle({ table.unpack(items) })
    local answer = pool[1]
    local choices = shuffle({ pool[1], pool[2], pool[3], pool[4] })
    print(string.format("\n[%d/%d] What does %s (%s) mean?", r, rounds, answer.arabic, answer.transliteration))
    for i, c in ipairs(choices) do print(string.format("  %d) %s", i, meaning(c, lang))) end
    io.write("> "); local pick = tonumber(io.read("l") or "")
    if pick and choices[pick] == answer then
      score = score + 1; print("Correct!")
    else
      print("Answer: " .. meaning(answer, lang))
    end
  end
  print(string.format("\nScore: %d/%d", score, rounds))
end

local function usage()
  print([[usage: lua5.4 asma.lua [--lang CODE] [--offline] <command>
commands:
  list               show every name in the response
  show N             show name number N
  search TEXT        search transliteration / meaning / Arabic
  quiz [ROUNDS]      multiple-choice meaning quiz (default 5)
languages: en ur fr de tr ms ru zh-CN ja]])
end

-- argument parsing
local lang, offline, rest = "en", false, {}
local i = 1
while i <= #arg do
  local a = arg[i]
  if a == "--lang" then i = i + 1; lang = arg[i] or "en"
  elseif a == "--offline" then offline = true
  else rest[#rest + 1] = a end
  i = i + 1
end
if not LANGS[lang] then io.stderr:write("unknown language '" .. lang .. "', using en\n"); lang = "en" end

local cmd = rest[1]
if not cmd or cmd == "help" then usage(); os.exit(0) end

math.randomseed(os.time())
local data, source = load_data(offline)
local items = data.items
io.stderr:write(string.format("%s - %d of %d names (from %s)\n", data.title, #items, data.total or #items, source))
if data.note then io.stderr:write(data.note .. "\n") end

if cmd == "list" then
  for _, it in ipairs(items) do show(it, lang) end
elseif cmd == "show" then
  local n = tonumber(rest[2]); local found
  for _, it in ipairs(items) do if it.number == n then found = it end end
  if found then show(found, lang) else print("name " .. tostring(rest[2]) .. " is not in this response") end
elseif cmd == "search" then
  search(items, table.concat(rest, " ", 2), lang)
elseif cmd == "quiz" then
  quiz(items, lang, tonumber(rest[2]) or 5)
else
  usage(); os.exit(1)
end
Enter fullscreen mode Exit fullscreen mode

A few design notes:

  • HTTP with curl. Lua has no HTTP client in its standard library. Instead of pulling in LuaSocket + LuaSec, we call curl -fsS --max-time 15 through io.popen. -f makes curl fail on HTTP errors, so p:close() returns false and we never cache an error page.
  • cjson.safe returns nil instead of throwing on bad JSON, so a broken response or a corrupted cache file is easy to handle.
  • Atomic cache writes. We write to .tmp and os.rename it, so an interrupted run never leaves half a JSON file behind.
  • Language fallback. meaning() tries the chosen language, then English, then the flat translation field.

4. Run it

$ lua5.4 asma.lua list
99 Names of Allah (Asma ul Husna) - 12 of 99 names (from network)
Showing 12 of 99 names. Full dataset available with premium subscription.
 1. الرَّحْمَنُ  (Ar-Rahman)
    The Entirely Merciful
 2. الرَّحِيمُ  (Ar-Raheem)
    The Especially Merciful
 3. الْمَلِكُ  (Al-Malik)
    The King
...
12. الْبَارِئُ  (Al-Bari)
    The Maker

$ lua5.4 asma.lua --lang ur show 3
 3. الْمَلِكُ  (Al-Malik)
    بادشاہ

$ lua5.4 asma.lua --lang fr --offline search roi
 3. الْمَلِكُ  (Al-Malik)
    Le Roi

$ lua5.4 asma.lua --lang ja search 王
 3. الْمَلِكُ  (Al-Malik)
    王
Enter fullscreen mode Exit fullscreen mode

The second and later runs say (from cache) and don't touch the network. The info lines go to stderr, so lua5.4 asma.lua list > names.txt gives you clean output.

The quiz (German this time):

$ lua5.4 asma.lua --lang de quiz 3

[1/3] What does الرَّحْمَنُ (Ar-Rahman) mean?
  1) Der Allerbarmer
  2) Der Mächtige
  3) Der Macher
  4) Der König
> 1
Correct!
...
Score: 2/3
Enter fullscreen mode Exit fullscreen mode

5. Ideas to extend it

  • Name of the day: pick items[(os.time() // 86400) % #items + 1] and print it from your shell profile.
  • Neovim: Neovim runs Lua natively, so the same load_data / meaning functions can feed a floating window or a dashboard plugin.
  • Spaced repetition: store wrong answers in a small JSON file next to the cache and ask them first next time.
  • More datasets with the same fetch-cache pattern: Azkar API, Duas API, Six Kalmas API or the free Quran Translation API. All 17 endpoints are listed on the APIs page and in the docs.

Notes

Top comments (0)