Crystal reads like Ruby but compiles to a fast native binary, and its standard library already has everything this project needs: HTTP::Client, HTTP::Server, JSON::Serializable and OptionParser. No shards, no shard.yml.
We will build duas, a small command line tool that:
- downloads the free sample from the SunnahSource Duas API (
https://sunnahsource.org/data/json/duas.json) - caches it and revalidates with
If-None-Match, so repeat runs get a304 Not Modified - prints a dua of the day that stays the same for the whole UTC day
- filters by category (
--category eating) and shows any of 9 languages (en, ur, fr, de, tr, ms, ru, zh-CN, ja) with an English fallback - works
--offlinefrom the cache - runs as a tiny JSON API (
--serve 8080) with/todayand/duas/:id
Tested with Crystal 1.14.0 on Linux.
1. Look at the data
curl -s https://sunnahsource.org/data/json/duas.json | head -c 400
The response is an object with title, description, is_free and an items array. Each item looks like this (translations shortened):
{
"id": 1,
"category": "Quranic",
"reference": "Quran 2:201",
"arabic": "رَبَّنَا آتِنَا فِي الدُّنْيَا حَسَنَةً وَفِي الْآخِرَةِ حَسَنَةً وَقِنَا عَذَابَ النَّارِ",
"transliteration": "Rabbana atina fid-dunya hasanatan wa fil-akhirati hasanatan wa qina 'adhaban-nar",
"translations": { "en": "Our Lord, give us good in this world and good in the Hereafter, and protect us from the punishment of the Fire.", "ur": "...", "ja": "..." }
}
Two things to handle: reference is present only on some items (the Quranic dua has it, "Before Eating" does not), and you should never assume every language key exists. Crystal's String? type makes the first point explicit.
The server also sends an ETag header:
curl -sI https://sunnahsource.org/data/json/duas.json | grep -i etag
# etag: W/"f97-..."
2. Project layout
duas/
src/duas.cr # model, fetch + cache, logic, server
src/main.cr # CLI
spec/duas_spec.cr # tests
3. The library: src/duas.cr
require "http/client"
require "http/server"
require "json"
require "file_utils"
module Duas
SOURCE = "https://sunnahsource.org/data/json/duas.json"
LANGS = %w(en ur fr de tr ms ru zh-CN ja)
CACHE_DIR = ENV.fetch("DUAS_CACHE", File.join(Dir.tempdir, "sunnahsource-duas"))
struct Dua
include JSON::Serializable
getter id : Int32
getter category : String
getter reference : String?
getter arabic : String
getter transliteration : String
getter translations : Hash(String, String)
# Requested language, then English, then any language present.
def text(lang : String) : String
translations[lang]? || translations["en"]? || translations.values.first? || ""
end
end
struct Feed
include JSON::Serializable
getter title : String
getter description : String
getter is_free : Bool
getter items : Array(Dua)
end
# Fetch with an ETag cache: 304 -> reuse the cached body.
def self.fetch(offline = false) : Feed
FileUtils.mkdir_p(CACHE_DIR)
body_path = File.join(CACHE_DIR, "duas.json")
etag_path = File.join(CACHE_DIR, "duas.etag")
unless offline
headers = HTTP::Headers{"User-Agent" => "duas-cr/1.0", "Accept" => "application/json"}
if File.exists?(body_path) && File.exists?(etag_path)
headers["If-None-Match"] = File.read(etag_path).strip
end
begin
res = HTTP::Client.get(SOURCE, headers: headers)
case res.status_code
when 200
File.write(body_path, res.body)
if etag = res.headers["ETag"]?
File.write(etag_path, etag)
end
STDERR.puts "[net] 200 fresh copy"
when 304
STDERR.puts "[net] 304 not modified, using cache"
else
STDERR.puts "[net] HTTP #{res.status_code}, falling back to cache"
end
rescue ex : Socket::Error | IO::Error
STDERR.puts "[net] #{ex.message}, falling back to cache"
end
end
raise "no cached copy yet; run once online" unless File.exists?(body_path)
parse(File.read(body_path))
end
def self.parse(json : String) : Feed
Feed.from_json(json)
end
# Same dua for everyone on the same day: day number modulo the list size.
def self.of_the_day(items : Array(Dua), date : Time) : Dua
raise "empty list" if items.empty?
days = (date.to_utc.at_beginning_of_day - Time.unix(0)).days.to_i
items[days % items.size]
end
def self.by_category(items : Array(Dua), q : String) : Array(Dua)
items.select { |d| d.category.downcase.includes?(q.downcase) }
end
def self.card(d : Dua, lang : String) : String
String.build do |s|
s << "#" << d.id << " [" << d.category << "]"
s << " (" << d.reference << ")" if d.reference
s << "\n" << d.arabic << "\n" << d.transliteration << "\n" << d.text(lang) << "\n"
end
end
def self.serve(feed : Feed, port : Int32)
server = HTTP::Server.new do |ctx|
lang = ctx.request.query_params["lang"]? || "en"
lang = "en" unless LANGS.includes?(lang)
ctx.response.content_type = "application/json; charset=utf-8"
ctx.response.headers["Access-Control-Allow-Origin"] = "*"
d = case ctx.request.path
when "/today" then of_the_day(feed.items, Time.utc)
when %r{^/duas/(\d+)$}
id = $1.to_i
feed.items.find { |x| x.id == id }
end
if d
{id: d.id, category: d.category, reference: d.reference, arabic: d.arabic,
transliteration: d.transliteration, lang: lang, translation: d.text(lang)}.to_json(ctx.response)
else
ctx.response.status = HTTP::Status::NOT_FOUND
{error: "not found"}.to_json(ctx.response)
end
end
addr = server.bind_tcp("127.0.0.1", port)
STDERR.puts "listening on http://#{addr}"
server.listen
end
end
Notes:
-
JSON::Serializablemaps the JSON straight tostructs.reference : String?makes the missing fieldnilinstead of an error. -
text(lang)tries the requested language, then English, then whatever exists. -
fetchsends the saved ETag. On304we reuse the cached body, on a network error we fall back to the cache, and with no cache at all we raise a clear error. -
of_the_dayuses whole days since the Unix epoch modulo the list size, so every user sees the same dua all day and it changes at midnight UTC. -
HTTP::Serverwith acaseon the path is enough for two routes.Access-Control-Allow-Origin: *lets a web page call it.
4. The CLI: src/main.cr
require "option_parser"
require "./duas"
lang = "en"
category = nil.as(String?)
offline = false
serve_port = nil.as(Int32?)
list = false
OptionParser.parse do |p|
p.banner = "Usage: duas [--lang ur] [--category eating] [--list] [--offline] [--serve 8080]"
p.on("--lang LANG", "en ur fr de tr ms ru zh-CN ja") { |v| lang = v }
p.on("--category Q", "filter by category") { |v| category = v }
p.on("--list", "print every dua") { list = true }
p.on("--offline", "use the cached copy only") { offline = true }
p.on("--serve PORT", "run a small JSON API") { |v| serve_port = v.to_i }
p.on("-h", "--help", "help") { puts p; exit }
end
begin
feed = Duas.fetch(offline)
rescue ex
STDERR.puts "error: #{ex.message}"
exit 1
end
if port = serve_port
Duas.serve(feed, port)
elsif q = category
found = Duas.by_category(feed.items, q)
if found.empty?
STDERR.puts "no dua in category '#{q}'"
exit 2
end
found.each { |d| puts Duas.card(d, lang) }
elsif list
feed.items.each { |d| puts Duas.card(d, lang) }
else
puts "Dua of the day (#{Time.utc.to_s("%Y-%m-%d")})"
puts Duas.card(Duas.of_the_day(feed.items, Time.utc), lang)
end
Exit codes: 0 ok, 1 no data (offline with no cache), 2 empty category filter. That makes it easy to use in scripts.
5. Tests: spec/duas_spec.cr
The specs use an inline sample with the same shape as the real response, so they run without the network:
require "spec"
require "../src/duas"
SAMPLE = <<-JSON
{"title":"Islamic Duas","description":"d","is_free":false,"items":[
{"id":1,"category":"Quranic","reference":"Quran 2:201","arabic":"a1","transliteration":"t1","translations":{"en":"E1","ur":"U1"}},
{"id":2,"category":"Before Eating","arabic":"a2","transliteration":"t2","translations":{"en":"E2"}},
{"id":3,"category":"Entering Home","arabic":"a3","transliteration":"t3","translations":{"de":"D3"}}]}
JSON
describe Duas do
feed = Duas.parse(SAMPLE)
it "parses items, optional reference" do
feed.items.size.should eq 3
feed.items[0].reference.should eq "Quran 2:201"
feed.items[1].reference.should be_nil
end
it "falls back to English, then any language" do
feed.items[0].text("ur").should eq "U1"
feed.items[1].text("ja").should eq "E2"
feed.items[2].text("fr").should eq "D3"
end
it "is stable for a day and rotates" do
t = Time.utc(2026, 11, 29, 1, 0, 0)
a = Duas.of_the_day(feed.items, t)
Duas.of_the_day(feed.items, Time.utc(2026, 11, 29, 23, 0, 0)).id.should eq a.id
Duas.of_the_day(feed.items, t + 1.day).id.should_not eq a.id
end
it "filters by category, case-insensitive" do
Duas.by_category(feed.items, "eating").map(&.id).should eq [2]
Duas.by_category(feed.items, "zzz").should be_empty
end
it "builds a card with reference" do
Duas.card(feed.items[0], "en").should contain "(Quran 2:201)"
end
end
crystal spec
# 5 examples, 0 failures, 0 errors, 0 pending
6. Build and run
crystal build src/main.cr -o duas --release
./duas
Real output (29 Nov 2026):
[net] 200 fresh copy
Dua of the day (2026-11-29)
#3 [Entering Home]
بِسْمِ اللَّهِ وَلَجْنَا وَبِسْمِ اللَّهِ خَرَجْنَا وَعَلَى اللَّهِ رَبِّنَا تَوَكَّلْنَا
Bismillahi walajna wa bismillahi kharajna wa 'alallahi rabbina tawakkalna
In the name of Allah we enter, in the name of Allah we leave, and upon our Lord we place our trust.
Run it again and the cache kicks in:
$ ./duas --lang ur --category eating
[net] 304 not modified, using cache
#2 [Before Eating]
بِسْمِ اللَّهِ
Bismillah
اللہ کے نام سے۔
The Quranic dua shows its reference:
$ ./duas --offline --list --lang ja
#1 [Quranic] (Quran 2:201)
رَبَّنَا آتِنَا فِي الدُّنْيَا حَسَنَةً وَفِي الْآخِرَةِ حَسَنَةً وَقِنَا عَذَابَ النَّارِ
Rabbana atina fid-dunya hasanatan wa fil-akhirati hasanatan wa qina 'adhaban-nar
我らの主よ、この世でも来世でも善を与え、火獄の懲罰から我らを守ってください。
...
Error cases:
$ ./duas --category zzz # exit 2
no dua in category 'zzz'
$ DUAS_CACHE=/tmp/empty ./duas --offline # exit 1
error: no cached copy yet; run once online
7. Serve it as a JSON API
./duas --serve 8089
curl -s "localhost:8089/today?lang=fr"
curl -s "localhost:8089/duas/1?lang=tr"
curl -s -w " %{http_code}" localhost:8089/duas/99
{"id":3,"category":"Entering Home","reference":null,"arabic":"بِسْمِ اللَّهِ وَلَجْنَا وَبِسْمِ اللَّهِ خَرَجْنَا وَعَلَى اللَّهِ رَبِّنَا تَوَكَّلْنَا","transliteration":"Bismillahi walajna wa bismillahi kharajna wa 'alallahi rabbina tawakkalna","lang":"fr","translation":"Au nom d'Allah nous entrons, au nom d'Allah nous sortons, et en Allah notre Seigneur nous plaçons notre confiance."}
{"id":1,"category":"Quranic","reference":"Quran 2:201","arabic":"رَبَّنَا آتِنَا فِي الدُّنْيَا حَسَنَةً وَفِي الْآخِرَةِ حَسَنَةً وَقِنَا عَذَابَ النَّارِ","transliteration":"Rabbana atina fid-dunya hasanatan wa fil-akhirati hasanatan wa qina 'adhaban-nar","lang":"tr","translation":"Rabbimiz! Bize dünyada da iyilik ver, ahirette de iyilik ver ve bizi ateş azabından koru."}
{"error":"not found"} 404
The server loads the data once at startup and binds to 127.0.0.1. Put it behind a reverse proxy if you expose it.
8. Ideas to extend it
- Show the Arabic in an RTL widget on your site using the
/todayendpoint. - Add morning and evening adhkar from the Azkar API.
- Show prayer-time reminders with the Prayer Times API.
- Add a Quran ayah with the Word by Word Quran API.
Links
- SunnahSource (Islamic APIs): https://sunnahsource.org/
- Duas API page: https://sunnahsource.org/apis/duas/
- Free sample JSON: https://sunnahsource.org/data/json/duas.json
- Azkar API: https://sunnahsource.org/apis/azkar/
- GitHub: https://github.com/sunnahsourceofficial-droid/sunnahsource-islamic-api
The sample file has a few duas. The full Duas API has more; see the Duas API page for details. If you build something with it, share it in the comments.
Top comments (0)