DEV Community

Cover image for Build a Terminal Azkar Counter in Python (stdlib only) with a Public JSON Sample
SunnahSource
SunnahSource

Posted on

Build a Terminal Azkar Counter in Python (stdlib only) with a Public JSON Sample

A lot of developers keep a terminal open all day. So why not keep your morning and evening adhkar there too? In this post we'll build a small Python command-line dhikr counter. It uses only the standard library (no pip install) and reads a public sample file from SunnahSource, a set of Islamic JSON APIs for Quran, Hadith, Duas, Azkar and more.

By the end you will have one script, azkar_cli.py, that can:

  • download the Azkar JSON and cache it for 24 hours (and keep working offline)
  • list the categories and filter by morning / evening
  • show the translation in any language key the JSON provides (en, ur, tr, ...)
  • run an interactive counter that stops when you reach the repeat count

Earlier posts in this series built a Flutter "Dua of the Day" widget and a vanilla JS 99 Names page. This one is plain Python, no framework.

1. Look at the data first

The Azkar API page loads a public preview file:

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

Important: this file is a sample. When I fetched it, it had 3 items, and the top-level is_free flag is false, because Azkar is a premium API. The sample is for designing and testing your UI. Here is its real shape, shortened to two languages per item:

{
  "title": "Azkar — Daily Remembrance",
  "description": "Morning and evening adhkar with translations",
  "is_free": false,
  "categories": ["morning", "evening", "after_prayer"],
  "items": [
    {
      "id": 1,
      "category": "morning",
      "repeat": 3,
      "arabic": "سُبْحَانَ اللَّهِ وَبِحَمْدِهِ",
      "transliteration": "Subhanallahi wa bihamdihi",
      "translations": {
        "en": "Glory be to Allah and praise Him.",
        "ur": "اللہ کی پاکی بیان کرتا ہوں اور اس کی حمد کرتا ہوں۔"
      }
    },
    {
      "id": 3,
      "category": "evening",
      "repeat": 100,
      "arabic": "أَسْتَغْفِرُ اللَّهَ",
      "transliteration": "Astaghfirullah",
      "translations": {
        "en": "I seek forgiveness from Allah.",
        "tr": "Allah'tan bağışlanma dilerim."
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

(Text copied as-is from azkar.json, items id: 1 and id: 3.)

A few things worth noticing before we write code:

  • translations is an object keyed by language code. The sample has en, ur, fr, de, tr, ms, ru, zh-CN and ja. Our language switch can be a dictionary lookup with an English fallback.
  • repeat tells us how many times the dhikr is recited. That's the target for our counter.
  • categories lists after_prayer, but the sample has no after_prayer items yet. Your code has to handle an empty category without crashing. This kind of edge case is exactly why it helps to read the real file first.
  • The items in the sample have no source/reference field. So in this post I cite every text by its id in the file, and I don't add references of my own.

2. Fetching with a cache (and an offline fallback)

We use urllib.request and save the raw response to ~/.cache/azkar_cli/azkar.json. If the cached copy is less than 24 hours old, we skip the network completely. If the network fails, we fall back to the last good copy:

def load_azkar(refresh: bool = False) -> dict:
    fresh = CACHE.exists() and time.time() - CACHE.stat().st_mtime < CACHE_TTL
    if fresh and not refresh:
        return json.loads(CACHE.read_text(encoding="utf-8"))
    ...
Enter fullscreen mode Exit fullscreen mode

Always read and write with encoding="utf-8". On Windows the default encoding is often not UTF-8, and Arabic and Urdu text will break without it.

We also send a User-Agent header. Some hosts reject Python's default Python-urllib/3.x agent, and a named agent is polite anyway.

3. The full script

Save this as azkar_cli.py. It needs Python 3.8+ and has no dependencies:

#!/usr/bin/env python3
"""azkar_cli.py - a tiny terminal dhikr counter using the SunnahSource Azkar sample."""
import argparse
import json
import sys
import time
import urllib.request
from pathlib import Path

SAMPLE_URL = "https://sunnahsource.org/data/json/azkar.json"
CACHE = Path.home() / ".cache" / "azkar_cli" / "azkar.json"
CACHE_TTL = 24 * 60 * 60  # refresh once a day


def load_azkar(refresh: bool = False) -> dict:
    """Return the parsed JSON, using a local cache when possible."""
    fresh = CACHE.exists() and time.time() - CACHE.stat().st_mtime < CACHE_TTL
    if fresh and not refresh:
        return json.loads(CACHE.read_text(encoding="utf-8"))
    try:
        req = urllib.request.Request(SAMPLE_URL, headers={"User-Agent": "azkar-cli/1.0"})
        with urllib.request.urlopen(req, timeout=10) as res:
            raw = res.read().decode("utf-8")
        data = json.loads(raw)
        CACHE.parent.mkdir(parents=True, exist_ok=True)
        CACHE.write_text(raw, encoding="utf-8")
        return data
    except (OSError, ValueError) as err:
        if CACHE.exists():  # offline? fall back to the last good copy
            print(f"(offline, using cache: {err})", file=sys.stderr)
            return json.loads(CACHE.read_text(encoding="utf-8"))
        sys.exit(f"Could not load azkar: {err}")


def translation(item: dict, lang: str) -> str:
    t = item.get("translations", {})
    return t.get(lang) or t.get("en", "")


def show(item: dict, lang: str) -> None:
    print(f"\n#{item['id']}  [{item['category']}]  x{item['repeat']}")
    print(f"  {item['arabic']}")
    print(f"  {item['transliteration']}")
    print(f"  {translation(item, lang)}")


def count(item: dict, lang: str) -> None:
    show(item, lang)
    target = item["repeat"]
    print(f"\nPress Enter to count, 'q' + Enter to stop.")
    done = 0
    while done < target:
        try:
            key = input(f"  {done}/{target} ")
        except EOFError:
            break
        if key.strip().lower() == "q":
            break
        done += 1
    print(f"  Finished {done}/{target}.")


def main() -> None:
    p = argparse.ArgumentParser(description="Terminal azkar reader and counter")
    p.add_argument("--category", help="e.g. morning, evening, after_prayer")
    p.add_argument("--lang", default="en", help="translation key, e.g. en, ur, tr")
    p.add_argument("--count", type=int, metavar="ID", help="start the counter for one item")
    p.add_argument("--list-categories", action="store_true")
    p.add_argument("--refresh", action="store_true", help="ignore the cache")
    args = p.parse_args()

    data = load_azkar(args.refresh)
    items = data["items"]

    if args.list_categories:
        for cat in data["categories"]:
            n = sum(1 for i in items if i["category"] == cat)
            print(f"{cat:<14} {n} item(s) in this file")
        return

    if args.count is not None:
        match = next((i for i in items if i["id"] == args.count), None)
        if not match:
            sys.exit(f"No item with id {args.count}")
        count(match, args.lang)
        return

    chosen = [i for i in items if not args.category or i["category"] == args.category]
    print(data["title"], "-", data["description"])
    if not chosen:
        print(f"No items for category '{args.category}' in this file.")
    for item in chosen:
        show(item, args.lang)


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

4. Try it

List the categories and how many items the sample actually has:

$ python3 azkar_cli.py --list-categories
morning        2 item(s) in this file
evening        1 item(s) in this file
after_prayer   0 item(s) in this file
Enter fullscreen mode Exit fullscreen mode

Show the morning adhkar with the Urdu translation:

$ python3 azkar_cli.py --category morning --lang ur
Azkar — Daily Remembrance - Morning and evening adhkar with translations

#1  [morning]  x3
  سُبْحَانَ اللَّهِ وَبِحَمْدِهِ
  Subhanallahi wa bihamdihi
  اللہ کی پاکی بیان کرتا ہوں اور اس کی حمد کرتا ہوں۔

#2  [morning]  x1
  اللَّهُمَّ بِكَ أَصْبَحْنَا وَبِكَ أَمْسَيْنَا وَبِكَ نَحْيَا وَبِكَ نَمُوتُ وَإِلَيْكَ النُّشُورُ
  Allahumma bika asbahna wa bika amsayna wa bika nahya wa bika namutu wa ilaykan-nushur
  اے اللہ! تیرے ہی ساتھ ہم نے صبح کی اور تیرے ہی ساتھ شام کی، تیرے ہی سے ہم زندہ ہیں اور تیرے ہی سے مریں گے اور تیری ہی طرف لوٹ کر جانا ہے۔
Enter fullscreen mode Exit fullscreen mode

(Output text comes straight from azkar.json, items id: 1 and id: 2.)

Start the counter for item 1 (repeat 3). Press Enter once per recitation:

$ python3 azkar_cli.py --count 1
...
Press Enter to count, 'q' + Enter to stop.
  0/3
  1/3
  2/3
  Finished 3/3.
Enter fullscreen mode Exit fullscreen mode

A note on terminals: most of them render Arabic letters fine, but many don't do full right-to-left shaping. If the Arabic looks reversed or disconnected, try a terminal with good bidi support (for example GNOME Terminal, Windows Terminal or iTerm2), or pipe the output into a file and open it in an editor.

5. Design choices, briefly

  • Standard library only. argparse, json, urllib and pathlib cover everything here. You can drop the script on any server or Raspberry Pi and run it.
  • Language fallback. translation() returns translations[lang] and falls back to en. So --lang xx still prints something useful.
  • Data-driven categories. Category names come from the JSON, not from hard-coded constants. When the full dataset adds after_prayer items, the CLI shows them with no code change.
  • EOFError handling. You can pipe input into the counter (printf '\n\n\n' | python3 azkar_cli.py --count 1), which makes it easy to test.

6. Ideas to extend it

  • Time-aware default: if no --category is given, pick morning before noon and evening after Asr. The Prayer Times API can give you the real Asr time.
  • Save progress: store today's counts in a small JSON file next to the cache, so you can stop and continue later.
  • Desktop notification: use notify-send (Linux) or osascript (macOS) to send a reminder at a fixed time.
  • Reuse the renderer: the Six Kalmas sample uses the same arabic / transliteration / translations fields, so show() works on it almost unchanged.

7. Going to production

The /data/json/*.json files are preview samples with only a few items. For the full Azkar dataset:

  1. Open the Azkar API page and fill in the Apply form with your project details.
  2. After your application is approved, your production endpoint and personal API key are sent to you by email.
  3. Put the endpoint in SAMPLE_URL (or an environment variable), and keep the key out of your source code.

The response format is the same JSON shape, so the script above keeps working.

Links

What would you add first: a rich-powered TUI, or a cron job that prints the morning adhkar when you open your terminal? Let me know in the comments.

Top comments (0)