Nim compiles to a small native binary, and its standard library already ships std/httpclient, std/json, std/parseopt and std/unittest. That is all this project needs: no nimble packages.
We will build qtopics, a command line tool for the free sample of the SunnahSource Quran Topics API (https://sunnahsource.org/data/json/quran-topics.json). It:
- lists Quran topics (patience, prayer, mercy, paradise) with their verse references
- shows titles and descriptions in 9 languages (en, ur, fr, de, tr, ms, ru, zh-CN, ja) with an English fallback
- answers "which topics cite verse 2:153?" with a reverse index
- exports Markdown with a quran.com link for every verse
- caches the JSON and revalidates it with
If-None-Match, so repeat runs get a304 Not Modified - works
--offlineand falls back to the cache if the network fails
Tested with Nim 2.2.4 on Linux.
1. Look at the data
curl -s https://sunnahsource.org/data/json/quran-topics.json | head -c 300
The response has title, description, is_free and an items array. One item, shortened to two languages:
{
"id": 1,
"slug": "patience",
"icon": "⏳",
"translations": {
"en": {
"title": "Patience (Sabr)",
"description": "Allah loves the patient. Patience is mentioned over 90 times in the Quran.",
"verses": ["2:153", "2:155", "3:200", "39:10"]
},
"de": {
"title": "Geduld (Sabr)",
"description": "Allah liebt die Geduldigen.",
"verses": ["2:153"]
}
}
}
Two things to notice:
- Verses are
surah:ayahstrings. - The English entry has the fullest
verseslist; some other languages list fewer. A reference like2:153means the same verse in every language, so we take titles and descriptions from the chosen language and the verse list from English.
The server also sends an ETag header, which we will use for caching:
curl -sI https://sunnahsource.org/data/json/quran-topics.json | grep -i etag
2. Project layout
qtopics/
src/core.nim # pure logic, no I/O
src/qtopics.nim # HTTP, cache, command line
tests/test_core.nim # std/unittest
Keeping parsing and formatting in core.nim means we can test it without the network.
3. The core module
## Pure logic: parsing, language fallback, reverse index, Markdown.
import std/[json, strutils, tables, algorithm]
const
Languages* = ["en", "ur", "fr", "de", "tr", "ms", "ru", "zh-CN", "ja"]
Fallback* = "en"
type
VerseRef* = object
surah*, ayah*: int
Topic* = object
id*: int
slug*, icon*, title*, description*: string
verses*: seq[VerseRef]
proc parseRef*(s: string): VerseRef =
## "2:153" -> (2, 153). Raises ValueError on bad input.
let parts = s.strip.split(':')
if parts.len != 2:
raise newException(ValueError, "bad verse ref: " & s)
result = VerseRef(surah: parseInt(parts[0]), ayah: parseInt(parts[1]))
if result.surah notin 1..114 or result.ayah < 1:
raise newException(ValueError, "verse ref out of range: " & s)
proc `$`*(v: VerseRef): string = $v.surah & ":" & $v.ayah
proc `<`*(a, b: VerseRef): bool =
(a.surah, a.ayah) < (b.surah, b.ayah)
proc quranComUrl*(v: VerseRef): string =
"https://quran.com/" & $v.surah & "/" & $v.ayah
proc pickLang(tr: JsonNode, lang: string): JsonNode =
if tr.hasKey(lang): tr[lang] else: tr[Fallback]
proc toTopic*(item: JsonNode, lang = Fallback): Topic =
## Title/description come from `lang` (English fallback).
## Verse refs always come from English: it has the fullest list,
## and a reference like 2:153 is the same in every language.
let tr = item["translations"]
let loc = pickLang(tr, lang)
result = Topic(
id: item["id"].getInt,
slug: item["slug"].getStr,
icon: item{"icon"}.getStr,
title: loc{"title"}.getStr(tr[Fallback]["title"].getStr),
description: loc{"description"}.getStr(tr[Fallback]["description"].getStr))
for r in tr[Fallback]{"verses"}.getElems:
result.verses.add parseRef(r.getStr)
proc loadTopics*(doc: JsonNode, lang = Fallback): seq[Topic] =
for item in doc["items"].getElems:
result.add toTopic(item, lang)
proc findTopic*(topics: seq[Topic], key: string): int =
## Match by slug or numeric id. Returns index or -1.
for i, t in topics:
if t.slug == key.toLowerAscii or $t.id == key:
return i
-1
proc verseIndex*(topics: seq[Topic]): OrderedTable[string, seq[string]] =
## "2:153" -> @["patience"], sorted by surah then ayah.
var refs: seq[VerseRef]
var tmp: Table[string, seq[string]]
for t in topics:
for v in t.verses:
if $v notin tmp: refs.add v
tmp.mgetOrPut($v, @[]).add t.slug
refs.sort()
for v in refs: result[$v] = tmp[$v]
proc toMarkdown*(topics: seq[Topic]): string =
result = "# Quran topics\n"
for t in topics:
result.add "\n## " & t.icon & " " & t.title & "\n\n" & t.description & "\n\n"
for v in t.verses:
result.add "- [" & $v & "](" & quranComUrl(v) & ")\n"
A few notes:
-
parseRefrejects anything that is notsurah:ayahwith a surah from 1 to 114. -
loc{"title"}.getStr(default)uses Nim's safe JSON access: if the key is missing we get the English value instead of an exception. -
verseIndexturns "topic -> verses" into "verse -> topics", sorted by surah and then ayah (not as strings, so2:43comes before2:110).
4. HTTP, cache and commands
## qtopics: browse the SunnahSource Quran Topics API from the terminal.
import std/[httpclient, json, os, parseopt, strutils, tables]
import core
const
Url = "https://sunnahsource.org/data/json/quran-topics.json"
Usage = """usage: qtopics [--lang=xx] [--offline] <command>
list all topics
show <slug|id> one topic with its verse references
verse <s:a> which topics cite this verse
index every cited verse and its topics
md Markdown export (links to quran.com)"""
proc cacheFiles(): (string, string) =
let dir = getCacheDir("qtopics")
createDir(dir)
(dir / "quran-topics.json", dir / "etag.txt")
proc fetchDoc(offline: bool): JsonNode =
let (bodyFile, etagFile) = cacheFiles()
if offline:
if not fileExists(bodyFile):
quit("no cache yet: run once without --offline", 2)
return parseFile(bodyFile)
let client = newHttpClient(timeout = 15_000, userAgent = "qtopics-nim/1.0")
defer: client.close()
if fileExists(etagFile) and fileExists(bodyFile):
client.headers["If-None-Match"] = readFile(etagFile).strip
try:
let resp = client.get(getEnv("QTOPICS_URL", Url))
case resp.code.int
of 304:
stderr.writeLine "cache: 304 Not Modified"
return parseFile(bodyFile)
of 200:
let body = resp.body
result = parseJson(body) # validate before caching
writeFile(bodyFile, body)
if resp.headers.hasKey("etag"):
writeFile(etagFile, resp.headers["etag"])
stderr.writeLine "cache: 200, saved ", body.len, " bytes"
else:
raise newException(IOError, "HTTP " & $resp.code)
except CatchableError as e:
if fileExists(bodyFile):
stderr.writeLine "network error (", e.msg, "), using cache"
return parseFile(bodyFile)
quit("network error: " & e.msg, 1)
proc main() =
var lang = Fallback
var offline = false
var args: seq[string]
for kind, key, val in getopt():
case kind
of cmdLongOption, cmdShortOption:
case key
of "lang", "l": lang = val
of "offline": offline = true
of "help", "h": echo Usage; return
else: quit("unknown option --" & key & "\n" & Usage, 2)
of cmdArgument: args.add key
of cmdEnd: discard
if lang notin Languages:
quit("unsupported language: " & lang & " (use " & Languages.join(", ") & ")", 2)
if args.len == 0: quit(Usage, 2)
let topics = loadTopics(fetchDoc(offline), lang)
case args[0]
of "list":
for t in topics:
echo t.id, ". ", t.icon, " ", t.title, " [", t.slug, "] ", t.verses.len, " verses"
of "show":
if args.len < 2: quit("show needs a slug or id", 2)
let i = topics.findTopic(args[1])
if i < 0: quit("no topic: " & args[1], 1)
let t = topics[i]
echo t.icon, " ", t.title, "\n", t.description, "\n"
for v in t.verses: echo " ", $v, " ", quranComUrl(v)
of "verse":
if args.len < 2: quit("verse needs a reference like 2:153", 2)
let key = try: $parseRef(args[1]) except ValueError as e: quit(e.msg, 2)
let idx = verseIndex(topics)
if key in idx: echo key, " -> ", idx[key].join(", ")
else: echo key, " is not cited by any topic"
of "index":
for v, slugs in verseIndex(topics): echo v.alignLeft(7), slugs.join(", ")
of "md":
stdout.write toMarkdown(topics)
else:
quit("unknown command: " & args[0] & "\n" & Usage, 2)
when isMainModule:
main()
How the cache works:
- The first run stores the body and the
ETagin the user cache directory (~/.cache/qtopicson Linux, fromgetCacheDir). - The next run sends
If-None-Match. If the data did not change, the server answers304with no body and we read the cached file. - The JSON is parsed before it is written, so a broken response never replaces a good cache.
- On any network error we fall back to the cache;
--offlineskips the network. -
QTOPICS_URLlets you point the tool at another copy of the file (handy for testing the fallback).
5. Tests
import std/[unittest, json, tables, strutils]
import ../src/core
let doc = parseJson("""{"items": [
{"id": 1, "slug": "patience", "icon": "P",
"translations": {
"en": {"title": "Patience (Sabr)", "description": "en desc", "verses": ["2:153", "2:155"]},
"de": {"title": "Geduld (Sabr)", "description": "de desc", "verses": ["2:153"]}}},
{"id": 2, "slug": "prayer", "icon": "S",
"translations": {
"en": {"title": "Prayer (Salah)", "description": "en", "verses": ["2:110", "2:43"]}}}]}""")
suite "core":
test "parseRef":
check $parseRef(" 2:153 ") == "2:153"
expect ValueError: discard parseRef("2-153")
expect ValueError: discard parseRef("115:1")
test "language with English verse refs":
let t = loadTopics(doc, "de")
check t[0].title == "Geduld (Sabr)"
check t[0].verses.len == 2 # refs come from en
check t[1].title == "Prayer (Salah)" # no de -> en fallback
test "findTopic by slug or id":
let t = loadTopics(doc)
check t.findTopic("PRAYER") == 1
check t.findTopic("1") == 0
check t.findTopic("mercy") == -1
test "verse index is sorted":
let idx = verseIndex(loadTopics(doc))
var keys: seq[string]
for k in idx.keys: keys.add k
check keys == @["2:43", "2:110", "2:153", "2:155"]
check idx["2:153"] == @["patience"]
test "markdown links":
let md = toMarkdown(loadTopics(doc))
check "- [2:153](https://quran.com/2/153)" in md
check md.startsWith("# Quran topics")
nim c -r tests/test_core.nim
[Suite] core
[OK] parseRef
[OK] language with English verse refs
[OK] findTopic by slug or id
[OK] verse index is sorted
[OK] markdown links
6. Build and run
std/httpclient needs -d:ssl for HTTPS (it uses the system OpenSSL):
nim c -d:ssl -d:release -o:qtopics src/qtopics.nim
First run downloads, the second one revalidates (cache messages go to stderr):
$ ./qtopics list
cache: 200, saved 5098 bytes
1. ⏳ Patience (Sabr) [patience] 4 verses
2. 🕌 Prayer (Salah) [prayer] 4 verses
3. 💚 Mercy of Allah [mercy] 3 verses
4. 🌴 Paradise (Jannah) [paradise] 4 verses
$ ./qtopics list --lang=ur
cache: 304 Not Modified
1. ⏳ صبر [patience] 4 verses
2. 🕌 نماز [prayer] 4 verses
3. 💚 اللہ کی رحمت [mercy] 3 verses
4. 🌴 جنت [paradise] 4 verses
One topic in German, with the full English verse list:
$ ./qtopics --lang=de show patience
⏳ Geduld (Sabr)
Allah liebt die Geduldigen.
2:153 https://quran.com/2/153
2:155 https://quran.com/2/155
3:200 https://quran.com/3/200
39:10 https://quran.com/39/10
Reverse lookups:
$ ./qtopics verse 2:43
2:43 -> prayer
$ ./qtopics verse 7:1
7:1 is not cited by any topic
$ ./qtopics index
2:25 paradise
2:43 prayer
2:110 prayer
2:153 patience
2:155 patience
3:15 paradise
3:200 patience
6:12 mercy
6:54 mercy
7:156 mercy
9:72 paradise
20:14 prayer
29:45 prayer
39:10 patience
55:46 paradise
Markdown export (French titles), ready for a README or a static site:
./qtopics md --lang=fr > topics.md
# Quran topics
## ⏳ Patience (Sabr)
Allah aime les patients.
- [2:153](https://quran.com/2/153)
- [2:155](https://quran.com/2/155)
- [3:200](https://quran.com/3/200)
- [39:10](https://quran.com/39/10)
Errors use exit codes, so the tool works well in scripts:
$ ./qtopics verse 200:1 # exit 2
verse ref out of range: 200:1
$ ./qtopics --lang=xx list # exit 2
unsupported language: xx (use en, ur, fr, de, tr, ms, ru, zh-CN, ja)
$ ./qtopics show nothing # exit 1
no topic: nothing
And with a broken network it keeps working from the cache:
$ QTOPICS_URL=https://nonexistent.invalid/x.json ./qtopics list
network error (...), using cache
1. ⏳ Patience (Sabr) [patience] 4 verses
...
7. Where to go next
- Show the Arabic text and a translation next to each reference with the Quran Translations API (the free sample covers Surah Al-Fatiha in 9 languages).
- Add a word-by-word view with the Word by Word Quran API, or commentary with the Tafseer API.
- Pair topics with related narrations from the Hadith API.
The sample JSON used here is free. For full data and other Islamic APIs (Quran, Hadith, Duas, Prayer Times, Hijri Calendar) see SunnahSource, and more examples are in the sunnahsource-islamic-api GitHub repo.
Top comments (0)