Rust is a great fit for small, fast command-line tools. In this tutorial we build islamic-stories, a CLI that reads two public JSON samples from SunnahSource:
- the Stories of the Prophets API (Qasas al-Anbiya):
https://sunnahsource.org/data/json/ambiya.json - the Sahaba API (companions of the Prophet ï·º):
https://sunnahsource.org/data/json/sahaba.json
The CLI lists the items, shows one story or biography in any of the 9 languages in the data, falls back to English when a language is missing, and keeps an on-disk cache so it still works offline.
All text the CLI prints comes straight from the JSON. The tutorial does not add any Islamic content of its own.
1. Look at the JSON first
Both files share the same envelope:
{ "title": "Stories of the Prophets (Ambiya)", "description": "Stories of Allah's prophets with translations in 9 languages", "is_free": false, "items": [ ... ] } Each item in ambiya.json has id, name_ar, name_en, order and a translations map. Each language entry has a title and a story:
{ "id": 1, "name_ar": "آدم", "name_en": "Adam (AS)", "order": 1, "translations": { "en": { "title": "Prophet Adam (AS)", "story": "..." }, "ur": { "title": "ØØ¶Ø±Øª آدم Ø¹Ù„ÛŒÛ Ø§Ù„Ø³Ù„Ø§Ù…", "story": "..." } } } Each item in sahaba.json has id, name_ar, name_en, a title (for example "First Caliph") and translations with a bio per language.
The language keys are en, ur, fr, de, tr, ms, ru, zh-CN and ja. These public files are samples (5 items each). Both APIs are premium ("is_free": false). For the full data and a production endpoint, apply for an API key.
2. Create the project
cargo new islamic-stories && cd islamic-stories cargo add serde --features derive cargo add serde_json cargo add ureq@2 ureq is a small blocking HTTP client. We don't need an async runtime for a CLI that makes one request.
3. The code
Everything fits in src/main.rs. The main ideas:
- Typed models with
serde::Deserializethat mirror the JSON fields exactly. One genericDataset<T>covers both files. -
pick()returns the requested language, orenif that key is missing. -
load()downloads the file and writes a copy to.cache-islamic-stories/. If the network fails, or you pass--offline, it reads the cached copy. You can change the folder with theSTORIES_CACHEenv var. - Pure functions (
list_prophets,show_prophet, ...) return strings, which makes them easy to unit-test.
use serde::Deserialize; use std::collections::HashMap; use std::{env, fs, path::PathBuf, process}; const BASE: &str = "https://sunnahsource.org/data/json"; const FALLBACK_LANG: &str = "en"; // ---------- Models (match the public sample JSON) ---------- #[derive(Debug, Deserialize)] struct Dataset<T> { title: String, description: String, is_free: bool, items: Vec<T>, } #[derive(Debug, Deserialize)] struct Prophet { id: u32, name_ar: String, name_en: String, order: u32, translations: HashMap<String, ProphetText>, } #[derive(Debug, Deserialize)] struct ProphetText { title: String, story: String, } #[derive(Debug, Deserialize)] struct Companion { id: u32, name_ar: String, name_en: String, title: String, translations: HashMap<String, CompanionText>, } #[derive(Debug, Deserialize)] struct CompanionText { bio: String, } // ---------- Language fallback ---------- /// Return the translation for `lang`, or English if that language is missing. fn pick<'a, T>(map: &'a HashMap<String, T>, lang: &str) -> Option<(&'a str, &'a T)> { map.get_key_value(lang) .or_else(|| map.get_key_value(FALLBACK_LANG)) .map(|(k, v)| (k.as_str(), v)) } // ---------- Fetch with a small on-disk cache ---------- fn cache_path(name: &str) -> PathBuf { let dir = env::var("STORIES_CACHE").unwrap_or_else(|_| ".cache-islamic-stories".into()); PathBuf::from(dir).join(format!("{name}.json")) } fn load(name: &str, offline: bool) -> Result<String, String> { let path = cache_path(name); if offline { return fs::read_to_string(&path) .map_err(|e| format!("no cached copy at {}: {e}", path.display())); } let url = format!("{BASE}/{name}.json"); match ureq::get(&url).set("Accept", "application/json").call() { Ok(resp) => { let body = resp.into_string().map_err(|e| e.to_string())?; if let Some(dir) = path.parent() { let _ = fs::create_dir_all(dir); } let _ = fs::write(&path, &body); Ok(body) } // Network down? Fall back to the last good copy. Err(err) => fs::read_to_string(&path).map_err(|_| format!("GET {url} failed: {err}")), } } fn parse<T: for<'de> Deserialize<'de>>(body: &str) -> Result<Dataset<T>, String> { serde_json::from_str(body).map_err(|e| format!("bad JSON: {e}")) } // ---------- Commands ---------- fn list_prophets(data: &Dataset<Prophet>, lang: &str) -> Vec<String> { let mut items: Vec<&Prophet> = data.items.iter().collect(); items.sort_by_key(|p| p.order); items .iter() .map(|p| { let title = pick(&p.translations, lang).map(|(_, t)| t.title.as_str()).unwrap_or(&p.name_en); format!("{:>2}. {} ({})", p.id, title, p.name_ar) }) .collect() } fn show_prophet(data: &Dataset<Prophet>, id: u32, lang: &str) -> Option<String> { let p = data.items.iter().find(|p| p.id == id)?; let (used, t) = pick(&p.translations, lang)?; Some(format!("{} ({})\n[{used}] {}\n\n{}", t.title, p.name_ar, p.name_en, t.story)) } fn list_sahaba(data: &Dataset<Companion>) -> Vec<String> { data.items .iter() .map(|c| format!("{:>2}. {} ({}) - {}", c.id, c.name_en, c.name_ar, c.title)) .collect() } fn show_companion(data: &Dataset<Companion>, id: u32, lang: &str) -> Option<String> { let c = data.items.iter().find(|c| c.id == id)?; let (used, t) = pick(&c.translations, lang)?; Some(format!("{} ({})\n{}\n[{used}]\n\n{}", c.name_en, c.name_ar, c.title, t.bio)) } fn usage() -> ! { eprintln!( "usage: islamic-stories <prophets|prophet ID|sahaba|companion ID> [--lang CODE] [--offline]\n\ languages: en ur fr de tr ms ru zh-CN ja (falls back to en)" ); process::exit(2); } fn main() { let args: Vec<String> = env::args().skip(1).collect(); let offline = args.iter().any(|a| a == "--offline"); let lang = args .iter() .position(|a| a == "--lang") .and_then(|i| args.get(i + 1)) .map(String::as_str) .unwrap_or(FALLBACK_LANG); let cmd = args.first().map(String::as_str).unwrap_or_else(|| usage()); let id = || -> u32 { args.get(1).and_then(|s| s.parse().ok()).unwrap_or_else(|| usage()) }; let result: Result<String, String> = match cmd { "prophets" | "prophet" => load("ambiya", offline).and_then(|b| parse::<Prophet>(&b)).and_then(|d| { if cmd == "prophets" { Ok(format!("{} - {}\n{}", d.title, d.description, list_prophets(&d, lang).join("\n"))) } else { show_prophet(&d, id(), lang).ok_or_else(|| "prophet id not found".into()) } }), "sahaba" | "companion" => load("sahaba", offline).and_then(|b| parse::<Companion>(&b)).and_then(|d| { if cmd == "sahaba" { let tier = if d.is_free { "free" } else { "premium (public sample)" }; Ok(format!("{} - {tier}\n{}", d.title, list_sahaba(&d).join("\n"))) } else { show_companion(&d, id(), lang).ok_or_else(|| "companion id not found".into()) } }), _ => usage(), }; match result { Ok(out) => println!("{out}"), Err(e) => { eprintln!("error: {e}"); process::exit(1); } } } #[cfg(test)] mod tests { use super::*; // Shape copied from ambiya.json; story text shortened to a placeholder. const PROPHETS: &str = r#"{"title":"Stories of the Prophets (Ambiya)","description":"d","is_free":false, "items":[{"id":2,"name_ar":"نوØ","name_en":"Nuh (AS)","order":2, "translations":{"en":{"title":"Prophet Nuh (AS)","story":"..."}}}, {"id":1,"name_ar":"آدم","name_en":"Adam (AS)","order":1, "translations":{"en":{"title":"Prophet Adam (AS)","story":"..."}, "ur":{"title":"ØØ¶Ø±Øª آدم Ø¹Ù„ÛŒÛ Ø§Ù„Ø³Ù„Ø§Ù…","story":"..."}}}]}"#; #[test] fn sorts_by_order_and_uses_language() { let d = parse::<Prophet>(PROPHETS).unwrap(); let lines = list_prophets(&d, "ur"); assert!(lines[0].contains("ØØ¶Ø±Øª آدم")); assert!(lines[1].contains("Prophet Nuh (AS)")); // no "ur" for Nuh -> English } #[test] fn falls_back_to_english() { let d = parse::<Prophet>(PROPHETS).unwrap(); let out = show_prophet(&d, 2, "de").unwrap(); assert!(out.contains("[en]")); assert!(show_prophet(&d, 99, "en").is_none()); } } 4. Run it
cargo run -q -- prophets Stories of the Prophets (Ambiya) - Stories of Allah's prophets with translations in 9 languages 1. Prophet Adam (AS) (آدم) 2. Prophet Nuh (AS) (نوØ) 3. Prophet Ibrahim (AS) (إبراهيم) 4. Prophet Musa (AS) (موسى) 5. Prophet Isa (AS) (عيسى) cargo run -q -- sahaba Sahaba — Noble Companions - premium (public sample) 1. Abu Bakr As-Siddiq (RA) (أبو بكر الصديق) - First Caliph 2. Umar ibn Al-Khattab (RA) (عمر بن الخطاب) - Second Caliph 3. Uthman ibn Affan (RA) (عثمان بن Ø¹ÙØ§Ù†) - Third Caliph 4. Ali ibn Abi Talib (RA) (علي بن أبي طالب) - Fourth Caliph 5. Bilal ibn Rabah (RA) (بلال بن رباØ) - First Muadhin To read one story or biography in a given language:
cargo run -q -- prophet 3 --lang ur # Urdu cargo run -q -- companion 1 --lang de # German cargo run -q -- prophet 1 --lang xx # unknown code -> English, marked [en] cargo run -q -- prophets --offline # uses the cached copy only The output shows which language was used (for example [ur]), so your users know when they are seeing the English fallback.
5. Test it
cargo test The two tests parse a fixture with the same shape as ambiya.json. They check that items are sorted by order, that the requested language is used, that English is the fallback, and that an unknown id returns None.
6. Ideas to extend it
- Add a
--jsonflag and print the selected item withserde_json::to_string_pretty. - Build a small Axum or Actix endpoint on top of the same models.
- Add the Seerah API for an Islamic history section.
- Pair it with the Duas API or the Hadith API for a daily-learning app.
Links
- SunnahSource (Islamic API for developers): https://sunnahsource.org/
- Stories of the Prophets API: https://sunnahsource.org/apis/ambiya/
- Sahaba API: https://sunnahsource.org/apis/sahaba/
- Pricing / plans: https://sunnahsource.org/pricing.html
- GitHub repo: https://github.com/sunnahsourceofficial-droid/sunnahsource-islamic-api
If you build something with it, share it in the comments. JazakAllah khair!