DEV Community

SunnahSource
SunnahSource

Posted on

Build a Seerah Reader CLI in Bash + jq (cached with If-Modified-Since, 9 languages, Markdown export)

Not every tool needs a framework. With bash, curl and jq you can build a small, fast command-line reader for JSON data, and it runs on any Linux box, macOS, WSL or CI runner.

In this tutorial we build seerah.sh, a CLI that reads two public JSON samples from SunnahSource:

  • the Seerah API (life of Prophet Muhammad ﷺ): https://sunnahsource.org/data/json/seerat-nabi.json
  • the Hijri Calendar API: https://sunnahsource.org/data/json/hijri-calendar.json

It will:

  • list and read Seerah chapters by id or slug
  • show text in 9 languages (en ur fr de tr ms ru zh-CN ja) and fall back to English
  • search titles and text
  • print the Hijri months
  • export everything as Markdown
  • cache the JSON and only re-download when it changed (If-Modified-Since / 304)
  • work offline from the cache

1. Look at the data first

Always start by looking at the real JSON:

curl -s https://sunnahsource.org/data/json/seerat-nabi.json | jq 'del(.chapters)'
Enter fullscreen mode Exit fullscreen mode
{
  "title": "Seerat un Nabi (SAW)",
  "description": "Life and biography of Prophet Muhammad (Peace Be Upon Him)",
  "is_free": false,
  "prophet": {
    "name_ar": "مُحَمَّدٌ",
    "name_en": "Muhammad",
    "full_title": "Prophet Muhammad (SAW)",
    "birth": "570 CE, Makkah",
    "death": "632 CE, Madinah"
  }
}
Enter fullscreen mode Exit fullscreen mode

Each item in chapters has an id, a slug and a translations object keyed by language, each with a title and content:

curl -s https://sunnahsource.org/data/json/seerat-nabi.json \
  | jq -c '.chapters[] | {id, slug, langs: (.translations | keys)}'
Enter fullscreen mode Exit fullscreen mode
{"id":1,"slug":"birth-early-life","langs":["de","en","fr","ja","ms","ru","tr","ur","zh-CN"]}
{"id":2,"slug":"first-revelation","langs":["de","en","fr","ja","ms","ru","tr","ur","zh-CN"]}
{"id":3,"slug":"hijrah","langs":["de","en","fr","ja","ms","ru","tr","ur","zh-CN"]}
{"id":4,"slug":"farewell-pilgrimage","langs":["de","en","fr","ja","ms","ru","tr","ur","zh-CN"]}
Enter fullscreen mode Exit fullscreen mode

The Hijri file has title, current_hijri and a months array with number, name_ar, name_en, days and translations (a plain string per language):

curl -s https://sunnahsource.org/data/json/hijri-calendar.json | jq -c '{current_hijri, first: .months[0]}'
Enter fullscreen mode Exit fullscreen mode

These are the free public samples (4 Seerah chapters, 5 Hijri months). The full datasets are part of the premium plans. See pricing.

2. Caching with curl -z

The trick that makes this pleasant is curl -z FILE. It sends an If-Modified-Since header with the mtime of FILE. If the server's copy did not change, it answers 304 Not Modified with no body. Add -R so the downloaded file keeps the server's Last-Modified time:

curl -sS -R -z cache.json -o new.json -w '%{http_code}' \
  https://sunnahsource.org/data/json/seerat-nabi.json
# first run: 200, next runs: 304
Enter fullscreen mode Exit fullscreen mode

We download into a temp file and only replace the cache when we got a 200 and the body is valid JSON (jq -e .). So a bad response never overwrites good data.

3. Picking a language with fallback

In jq, // is the "alternative" operator. We define a small function once and reuse it:

def tr($l): (.translations[$l] // .translations.en);
Enter fullscreen mode Exit fullscreen mode

--lang xx (an unknown code) quietly falls back to English.

4. The full script

#!/usr/bin/env bash
# seerah.sh - read the Seerah (life of the Prophet ﷺ) and Hijri months from public JSON
# Needs: bash 4+, curl, jq
set -euo pipefail

BASE="https://sunnahsource.org/data/json"
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/seerah-sh"
LANG_CODE="en"
OFFLINE=0
mkdir -p "$CACHE_DIR"

die() { echo "error: $*" >&2; exit 1; }

# fetch NAME -> prints path of a cached JSON file
# Uses If-Modified-Since (curl -z) so unchanged files return 304 and are not re-downloaded.
fetch() {
  local name="$1" file="$CACHE_DIR/$1.json" tmp
  if [[ $OFFLINE -eq 1 ]]; then
    [[ -s "$file" ]] || die "no cached copy of $name.json (run once online)"
    echo "$file"; return
  fi
  local args=(-sS -R --compressed -m 20) code
  [[ -s "$file" ]] && args+=(-z "$file")   # send If-Modified-Since = cache file mtime
  tmp="$(mktemp)"
  code=$(curl "${args[@]}" -o "$tmp" -w '%{http_code}' "$BASE/$name.json") || code="000"
  if [[ "$code" == "200" ]] && jq -e . "$tmp" >/dev/null 2>&1; then
    mv "$tmp" "$file"
  else
    rm -f "$tmp"
    [[ -s "$file" ]] || die "download failed (HTTP $code) and no cache for $name.json"
    [[ "$code" == "304" ]] || echo "warning: HTTP $code, using cached $name.json" >&2
  fi
  echo "$file"
}

# jq helper: pick translation for $lang, fall back to English
JQ_TR='def tr($l): (.translations[$l] // .translations.en);'

cmd_list() {
  local f; f=$(fetch seerat-nabi)
  jq -r --arg l "$LANG_CODE" "$JQ_TR"'
    "\(.title) - \(.prophet.full_title) (\(.prophet.birth) - \(.prophet.death))",
    (.chapters[] | "  \(.id). \(tr($l).title)  [\(.slug)]")' "$f"
}

cmd_read() {
  local key="${1:-}" f; [[ -n "$key" ]] || die "usage: read <id|slug>"
  f=$(fetch seerat-nabi)
  jq -r -e --arg k "$key" --arg l "$LANG_CODE" "$JQ_TR"'
    .chapters[] | select((.id|tostring) == $k or .slug == $k)
    | tr($l) as $t | "\($t.title)\n\("=" * ($t.title|length))\n\n\($t.content)"' "$f" \
    || die "chapter '$key' not found"
}

cmd_search() {
  local q="${1:-}" f; [[ -n "$q" ]] || die "usage: search <word>"
  f=$(fetch seerat-nabi)
  jq -r --arg q "$q" --arg l "$LANG_CODE" "$JQ_TR"'
    .chapters[] | tr($l) as $t
    | select(($t.title + " " + $t.content) | ascii_downcase | contains($q|ascii_downcase))
    | "\(.id). \($t.title): \($t.content[0:90])..."' "$f"
}

cmd_months() {
  local f; f=$(fetch hijri-calendar)
  jq -r --arg l "$LANG_CODE" '
    "\(.title) (current: \(.current_hijri))",
    (.months[] | "  \(.number). \(.name_en) (\(.name_ar)) - \(.days) days - \(.translations[$l] // .translations.en)")' "$f"
}

cmd_markdown() {
  local f; f=$(fetch seerat-nabi)
  jq -r --arg l "$LANG_CODE" "$JQ_TR"'
    "# \(.title)\n",
    (.chapters[] | tr($l) as $t | "## \(.id). \($t.title)\n\n\($t.content)\n"),
    "_Source: https://sunnahsource.org/apis/seerat-nabi/_"' "$f"
}

usage() {
  cat <<USAGE
usage: seerah.sh [--lang CODE] [--offline] <command> [arg]
commands:
  list              chapters of the Seerah
  read <id|slug>    one chapter
  search <word>     search titles and text
  months            Hijri months
  markdown          export all chapters as Markdown
languages: en ur fr de tr ms ru zh-CN ja (falls back to en)
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --lang) LANG_CODE="${2:?}"; shift 2 ;;
    --offline) OFFLINE=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) break ;;
  esac
done

case "${1:-}" in
  list) cmd_list ;;
  read) cmd_read "${2:-}" ;;
  search) cmd_search "${2:-}" ;;
  months) cmd_months ;;
  markdown) cmd_markdown ;;
  *) usage; exit 1 ;;
esac
Enter fullscreen mode Exit fullscreen mode

Make it executable:

chmod +x seerah.sh
Enter fullscreen mode Exit fullscreen mode

5. Try it

./seerah.sh list
Enter fullscreen mode Exit fullscreen mode
Seerat un Nabi (SAW) - Prophet Muhammad (SAW) (570 CE, Makkah - 632 CE, Madinah)
  1. Birth & Early Life  [birth-early-life]
  2. First Revelation  [first-revelation]
  3. Hijrah to Madinah  [hijrah]
  4. Farewell Pilgrimage  [farewell-pilgrimage]
Enter fullscreen mode Exit fullscreen mode

Read a chapter by id or slug:

./seerah.sh read 3
./seerah.sh --lang ur read hijrah
./seerah.sh --lang tr read farewell-pilgrimage
Enter fullscreen mode Exit fullscreen mode
Hijrah to Madinah
=================

After years of persecution in Makkah, the Prophet (SAW) migrated to Madinah in 622 CE with Abu Bakr (RA). This marks the beginning of the Islamic calendar. He established the first Muslim community and Masjid an-Nabawi.
Enter fullscreen mode Exit fullscreen mode

Search (case-insensitive):

./seerah.sh search makkah
Enter fullscreen mode Exit fullscreen mode
1. Birth & Early Life: Prophet Muhammad (SAW) was born in Makkah in the Year of the Elephant (570 CE). His father...
3. Hijrah to Madinah: After years of persecution in Makkah, the Prophet (SAW) migrated to Madinah in 622 CE with...
Enter fullscreen mode Exit fullscreen mode

Hijri months:

./seerah.sh months
Enter fullscreen mode Exit fullscreen mode
Hijri Calendar (current: 1447 AH)
  1. Muharram (مُحَرَّم) - 30 days - Sacred month — Islamic New Year, Ashura
  2. Safar (صَفَر) - 29 days - Second month of Islamic calendar
  3. Rabi al-Awwal (رَبِيع الأَوَّل) - 30 days - Month of Prophet's birth (SAW)
  9. Ramadan (رَمَضَان) - 30 days - Month of fasting — Quran revealed
  12. Dhul Hijjah (ذُو الحِجَّة) - 29 days - Month of Hajj — Eid al-Adha
Enter fullscreen mode Exit fullscreen mode

Export to Markdown (handy for a static site, a README or a Telegram bot):

./seerah.sh --lang en markdown > seerah.md
Enter fullscreen mode Exit fullscreen mode

Offline (after one online run):

./seerah.sh --offline list
Enter fullscreen mode Exit fullscreen mode

6. Ideas to extend it

  • Pipe markdown into pandoc to make an EPUB or PDF.
  • Add fzf for an interactive chapter picker: ./seerah.sh list | fzf.
  • Run months in a cron job or a GitHub Action and post it to a channel.
  • Use the same pattern for other datasets, for example the Sahaba API, the Stories of the Prophets API or the Duas API.

Notes

  • Arabic and Urdu text prints fine in any UTF-8 terminal. Right-to-left shaping depends on your terminal.
  • Please cache. The -z check keeps traffic tiny.
  • The public JSON files are samples. For full data and an API key, apply on the API pages or see pricing. For a dataset that is not listed, use the custom API request form.

More examples and the list of endpoints are in the GitHub repo: sunnahsourceofficial-droid/sunnahsource-islamic-api.

Top comments (0)