DEV Community

SunnahSource
SunnahSource

Posted on

Build a Prophets & Companions Reader CLI in Tcl 8.6 with tcllib JSON, TLS, a 24h Cache and 9 Languages

Tcl is still everywhere: build systems, EDA tools, test rigs, embedded boxes. It also makes a nice little HTTP + JSON client. In this tutorial we build bios.tcl, a terminal reader for two APIs from QuraniAPI:

The tool:

  • downloads both datasets over HTTPS and caches them for 24 hours
  • falls back to the old cache if the network fails, and has an --offline mode
  • validates the response (success flag, items array) before caching it
  • lists, shows and searches entries, with any of 9 languages: en ur fr de tr ms ru zh-CN ja (falls back to English)
  • exports everything to a UTF-8 Markdown file
  • comes with 6 tcltest unit tests that run without the network

Tested with Tcl 8.6.16, tcllib 2.0 (json 1.3.6) and tcl-tls 1.8.0 on Debian.

Setup

Tcl ships http, but HTTPS needs tls and JSON parsing needs tcllib:

sudo apt-get install tcl tcllib tcl-tls     # Debian / Ubuntu
# other systems: install Tcl 8.6 plus the tcllib and tcltls packages
Enter fullscreen mode Exit fullscreen mode

The endpoints

GET https://quranicapi.online/api/serve.php?slug=ambiya&lang=all
GET https://quranicapi.online/api/serve.php?slug=sahaba&lang=all
Enter fullscreen mode Exit fullscreen mode

lang can be all or a single language code. CORS is open and the response is plain JSON. A trimmed Sahaba response:

{
  "title": "Sahaba — Noble Companions",
  "items": [
    {
      "id": 5,
      "name_ar": "بلال بن رباح",
      "name_en": "Bilal ibn Rabah (RA)",
      "title": "First Muadhin",
      "translations": {
        "en": {
          "bio": "Bilal was an Ethiopian companion who endured severe torture for his faith. The Prophet (SAW) chose him as the first muadhin (caller to prayer) of Islam."
        },
        "ur": {
          "bio": "بلال حبشی صحابی تھے جنہوں نے ایمان پر شدید اذیتیں برداشت کیں۔ رسول اللہ صلی اللہ علیہ وسلم نے انہیں اسلام کے پہلے مؤذن منتخب کیا۔"
        }
      }
    }
  ],
  "success": true
}
Enter fullscreen mode Exit fullscreen mode

Ambiya items look the same, except each translation has a title and a story, and there is an order field:

{
  "id": 1,
  "name_ar": "آدم",
  "name_en": "Adam (AS)",
  "order": 1,
  "translations": {
    "en": {
      "title": "Prophet Adam (AS)",
      "story": "Adam was the first human and first prophet. Allah created him from clay, taught him all names, and placed him in Paradise. After eating from the forbidden tree, Adam and Hawwa repented and were sent to Earth as Allah's vicegerent."
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The public response is a sample (5 prophets and 5 companions). Our code only reads items, so it works the same with the full dataset.

The library: bioslib.tcl

All the logic lives in a small namespace so we can test it. Three details matter:

  1. ::http::register https 443 [list ::tls::socket -autoservername true] turns on HTTPS with SNI.
  2. -binary 1 makes geturl hand us raw bytes. We then decode UTF-8 exactly once. Without it, Tcl's http package may already decode the body (because the server sends charset=utf-8), and decoding again turns the Arabic and Urdu text into garbage. I hit exactly this bug while writing the tutorial: json2dict failed with unexpected token on the first Arabic name.
  3. We parse and check the JSON before writing the cache, so a bad response never replaces a good cache.
# bioslib.tcl - small library for the QuraniAPI Ambiya + Sahaba JSON APIs
package require Tcl 8.6
package require http
package require tls
package require json

namespace eval bios {
    variable base   "https://quranicapi.online/api/serve.php"
    variable maxAge [expr {24 * 3600}]
    variable langs  {en ur fr de tr ms ru zh-CN ja}
    variable cacheDir [file join [pwd] .bios-cache]
    ::http::register https 443 [list ::tls::socket -autoservername true]
}

# Download one dataset (ambiya or sahaba) and return the raw JSON text.
proc bios::download {slug} {
    variable base
    set url "$base?[::http::formatQuery slug $slug lang all]"
    set tok [::http::geturl $url -timeout 15000 -binary 1 \
                 -headers {Accept application/json User-Agent bios-tcl/1.0}]
    try {
        if {[::http::status $tok] ne "ok"} {
            error "network: [::http::status $tok] [::http::error $tok]"
        }
        if {[::http::ncode $tok] != 200} {
            error "HTTP [::http::ncode $tok] for $url"
        }
        # -binary 1 gives raw bytes, so we decode UTF-8 exactly once
        return [encoding convertfrom utf-8 [::http::data $tok]]
    } finally {
        ::http::cleanup $tok
    }
}

proc bios::readFile {path} {
    set f [open $path r]; fconfigure $f -encoding utf-8
    try { return [read $f] } finally { close $f }
}
proc bios::writeFile {path text} {
    set f [open $path w]; fconfigure $f -encoding utf-8
    try { puts -nonewline $f $text } finally { close $f }
}

# Parse and check the response; returns the list of item dicts.
proc bios::parse {jsonText} {
    set d [::json::json2dict $jsonText]
    if {![dict exists $d success] || ![dict get $d success]} {
        error "API did not return success"
    }
    if {![dict exists $d items]} { error "response has no items" }
    return [dict get $d items]
}

# Cached fetch: fresh cache (<24h) -> use it; otherwise download;
# if the download fails, fall back to a stale cache. offline=1 never downloads.
proc bios::fetch {slug {offline 0}} {
    variable cacheDir; variable maxAge
    file mkdir $cacheDir
    set path [file join $cacheDir $slug.json]
    set have [file exists $path]
    set fresh [expr {$have && [clock seconds] - [file mtime $path] < $maxAge}]
    if {$fresh || ($offline && $have)} {
        return [parse [readFile $path]]
    }
    if {$offline} { error "offline and no cache for $slug" }
    try {
        set text [download $slug]
        set items [parse $text]          ;# validate before caching
        writeFile $path $text
        return $items
    } on error {msg} {
        if {$have} {
            puts stderr "warning: $msg - using stale cache for $slug"
            return [parse [readFile $path]]
        }
        error $msg
    }
}

# Pick a translation with fallback to English.
proc bios::tr {item lang} {
    set t [dict get $item translations]
    if {[dict exists $t $lang]} { return [dict get $t $lang] }
    return [dict get $t en]
}

# Normalise one item from either dataset into: kind id name name_ar title text
proc bios::card {kind item lang} {
    set t [tr $item $lang]
    if {$kind eq "ambiya"} {
        set title [dict get $t title]; set text [dict get $t story]
    } else {
        set title [dict get $item title]; set text [dict get $t bio]
    }
    return [dict create kind $kind id [dict get $item id] \
                name [dict get $item name_en] name_ar [dict get $item name_ar] \
                title $title text $text]
}

proc bios::cards {data lang} {
    set out {}
    foreach kind {ambiya sahaba} {
        if {![dict exists $data $kind]} continue
        foreach item [dict get $data $kind] { lappend out [card $kind $item $lang] }
    }
    return $out
}

# Case-insensitive search in the English name, title and text.
proc bios::search {cards word} {
    set word [string tolower $word]
    lmap c $cards {
        set hay [string tolower "[dict get $c name] [dict get $c title] [dict get $c text]"]
        if {[string first $word $hay] < 0} continue
        set c
    }
}

proc bios::markdown {cards lang} {
    set md "# Prophets and Companions ($lang)\n\n"
    append md "Data: QuraniAPI (https://quranicapi.online/) - Ambiya and Sahaba APIs.\n"
    foreach c $cards {
        append md "\n## [dict get $c name] - [dict get $c name_ar]\n\n"
        append md "*[dict get $c title]* ([dict get $c kind] #[dict get $c id])\n\n"
        append md "[dict get $c text]\n"
    }
    return $md
}
Enter fullscreen mode Exit fullscreen mode

bios::card turns both datasets into one shape (kind id name name_ar title text), so the rest of the code doesn't care whether it is showing a prophet or a companion.

The CLI: bios.tcl

#!/usr/bin/env tclsh
# bios.tcl - Prophets (Ambiya) and Companions (Sahaba) reader
source [file join [file dirname [info script]] bioslib.tcl]

proc usage {} {
    puts stderr "usage: bios.tcl ?--lang xx? ?--offline? list|show KIND ID|search WORD|export FILE.md"
    exit 2
}

set lang en; set offline 0; set rest {}
for {set i 0} {$i < [llength $argv]} {incr i} {
    set a [lindex $argv $i]
    switch -- $a {
        --lang    { set lang [lindex $argv [incr i]] }
        --offline { set offline 1 }
        default   { lappend rest $a }
    }
}
if {$lang ni $bios::langs} {
    puts stderr "unknown language $lang (use one of: $bios::langs)"; exit 2
}
if {![llength $rest]} usage

fconfigure stdout -encoding utf-8
try {
    set data [dict create ambiya [bios::fetch ambiya $offline] \
                          sahaba [bios::fetch sahaba $offline]]
} on error {msg} {
    puts stderr "error: $msg"; exit 1
}
set cards [bios::cards $data $lang]

switch -- [lindex $rest 0] {
    list {
        foreach c $cards {
            puts [format "%-7s %2d  %-28s %s" [dict get $c kind] [dict get $c id] \
                      [dict get $c name] [dict get $c title]]
        }
    }
    show {
        lassign [lrange $rest 1 2] kind id
        set hit [lsearch -inline -glob $cards "kind $kind id $id *"]
        if {$hit eq ""} { puts stderr "not found: $kind $id"; exit 1 }
        puts "[dict get $hit name]  [dict get $hit name_ar]"
        puts "[dict get $hit title]\n"
        puts [dict get $hit text]
    }
    search {
        set word [lindex $rest 1]
        set enCards [bios::cards $data en]
        foreach c [bios::search $enCards $word] {
            puts "[dict get $c kind] [dict get $c id]: [dict get $c name] - [dict get $c title]"
        }
    }
    export {
        set file [lindex $rest 1]
        if {$file eq ""} usage
        bios::writeFile $file [bios::markdown $cards $lang]
        puts "wrote $file ([llength $cards] entries)"
    }
    default usage
}
Enter fullscreen mode Exit fullscreen mode

Run it

$ tclsh bios.tcl list
ambiya   1  Adam (AS)                    Prophet Adam (AS)
ambiya   2  Nuh (AS)                     Prophet Nuh (AS)
ambiya   3  Ibrahim (AS)                 Prophet Ibrahim (AS)
ambiya   4  Musa (AS)                    Prophet Musa (AS)
ambiya   5  Isa (AS)                     Prophet Isa (AS)
sahaba   1  Abu Bakr As-Siddiq (RA)      First Caliph
sahaba   2  Umar ibn Al-Khattab (RA)     Second Caliph
sahaba   3  Uthman ibn Affan (RA)        Third Caliph
sahaba   4  Ali ibn Abi Talib (RA)       Fourth Caliph
sahaba   5  Bilal ibn Rabah (RA)         First Muadhin

$ tclsh bios.tcl --lang ur show sahaba 5
Bilal ibn Rabah (RA)  بلال بن رباح
First Muadhin

بلال حبشی صحابی تھے جنہوں نے ایمان پر شدید اذیتیں برداشت کیں۔ رسول اللہ صلی اللہ علیہ وسلم نے انہیں اسلام کے پہلے مؤذن منتخب کیا۔

$ tclsh bios.tcl search caliph
sahaba 1: Abu Bakr As-Siddiq (RA) - First Caliph
sahaba 2: Umar ibn Al-Khattab (RA) - Second Caliph
sahaba 3: Uthman ibn Affan (RA) - Third Caliph
sahaba 4: Ali ibn Abi Talib (RA) - Fourth Caliph

$ tclsh bios.tcl --lang ja show ambiya 3
Ibrahim (AS)  إبراهيم
é è¨€è€…ã‚¤ãƒ–ãƒ©ãƒ¼ãƒ’ãƒ¼ãƒ 

ã‚¤ãƒ–ãƒ©ãƒ¼ãƒ’ãƒ¼ãƒ ã¯é è¨€è€…ã®çˆ¶ã€‚ã‚«ãƒ¼ãƒã‚’å»ºè¨­ã—ãŸã€‚

$ tclsh bios.tcl --lang fr --offline export bios_fr.md
wrote bios_fr.md (10 entries)
Enter fullscreen mode Exit fullscreen mode

The start of bios_fr.md:

# Prophets and Companions (fr)

Data: QuraniAPI (https://quranicapi.online/) - Ambiya and Sahaba APIs.

## Adam (AS) - آدم

*Prophète Adam (PSL)* (ambiya #1)

Adam fut le premier homme et le premier prophète. Allah le créa d'argile et le plaça au Paradis.
Enter fullscreen mode Exit fullscreen mode

If the network is down and the cache is older than 24 hours, you still get data plus a warning on stderr:

warning: connect failed due to unexpected EOF - using stale cache for sahaba
Enter fullscreen mode Exit fullscreen mode

Tests: bios.test

tcltest comes with Tcl. The tests use small inline fixtures, so they run offline:

package require tcltest
namespace import ::tcltest::*
source [file join [file dirname [info script]] bioslib.tcl]

set fixture {{"success":true,"items":[
 {"id":1,"name_ar":"آدم","name_en":"Adam (AS)","order":1,
  "translations":{"en":{"title":"Prophet Adam (AS)","story":"The first human."},
                  "ur":{"title":"حضرت آدم","story":"پہلے انسان"}}}]}}
set sfix {{"success":true,"items":[
 {"id":5,"name_ar":"بلال","name_en":"Bilal ibn Rabah (RA)","title":"First Muadhin",
  "translations":{"en":{"bio":"He called the adhan."}}}]}}

test parse-ok {items are returned} {
    llength [bios::parse $fixture]
} 1
test parse-fail {success false is an error} -body {
    bios::parse {{"success":false}}
} -returnCodes error -result {API did not return success}
test tr-fallback {missing language falls back to English} {
    set item [lindex [bios::parse $sfix] 0]
    dict get [bios::tr $item ja] bio
} {He called the adhan.}
test card-ambiya-ur {ambiya card uses translated title and story} {
    set c [bios::card ambiya [lindex [bios::parse $fixture] 0] ur]
    list [dict get $c title] [dict get $c text]
} {{حضرت آدم} {پہلے انسان}}
test search {search is case-insensitive} {
    set data [dict create ambiya [bios::parse $fixture] sahaba [bios::parse $sfix]]
    lmap c [bios::search [bios::cards $data en] ADHAN] { dict get $c name }
} {{Bilal ibn Rabah (RA)}}
test offline-stale {offline mode reads an old cache} {
    set bios::cacheDir [makeDirectory cache]
    bios::writeFile [file join $bios::cacheDir ambiya.json] $fixture
    file mtime [file join $bios::cacheDir ambiya.json] [expr {[clock seconds] - 90000}]
    dict get [lindex [bios::fetch ambiya 1] 0] name_en
} {Adam (AS)}
cleanupTests
Enter fullscreen mode Exit fullscreen mode
$ tclsh bios.test
bios.test:  Total   6   Passed  6   Skipped 0   Failed  0
Enter fullscreen mode Exit fullscreen mode

Ideas to extend it

  • Wrap it in Tk (package require Tk) for a small desktop reader with a language dropdown.
  • Add the Seerat un Nabi API as a third kind; bios::card is the only proc that needs a new branch.
  • Serve the cards as JSON from a tiny socket -server handler for a local kiosk screen.

Notes

Top comments (0)