Code Examples
Complete working examples for common use cases with the Sabdasakha API.
Dictionary Lookup with Fallback
Look up a word and handle the case when it's not found:
import requests
def lookup_word(word):
"""
Look up a Nepali word. Returns definition or suggestions if not found.
"""
url = f"https://sabdasakha.com/api/v1/dictionary/word/{word}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return {
"found": True,
"word": data["word"],
"definitions": data["definitions"],
"part_of_speech": data.get("part_of_speech", "")
}
elif response.status_code == 404:
data = response.json()
return {
"found": False,
"word": word,
"suggestions": data.get("similar_words", [])
}
else:
raise Exception(f"API error: {response.status_code}")
# Usage
result = lookup_word("नेपाल")
if result["found"]:
print(f"{result['word']}: {', '.join(result['definitions'])}")
else:
print(f"Not found. Did you mean: {', '.join(result['suggestions'])}?")
async function lookupWord(word) {
const url = `https://sabdasakha.com/api/v1/dictionary/word/${encodeURIComponent(word)}`;
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
return {
found: true,
word: data.word,
definitions: data.definitions,
partOfSpeech: data.part_of_speech || ""
};
}
if (response.status === 404) {
const data = await response.json();
return {
found: false,
word: word,
suggestions: data.similar_words || []
};
}
throw new Error(`API error: ${response.status}`);
}
// Usage
const result = await lookupWord("नेपाल");
if (result.found) {
console.log(`${result.word}: ${result.definitions.join(", ")}`);
} else {
console.log(`Not found. Did you mean: ${result.suggestions.join(", ")}?`);
}
Search-as-you-Type Autocomplete
Implement debounced autocomplete for a search input:
class NepaliAutocomplete {
constructor(inputElement, suggestionsContainer) {
this.input = inputElement;
this.container = suggestionsContainer;
this.debounceTimer = null;
this.input.addEventListener("input", (e) => this.onInput(e));
}
onInput(event) {
const query = event.target.value.trim();
// Clear previous timer
clearTimeout(this.debounceTimer);
// Clear suggestions if query is too short
if (query.length < 2) {
this.container.innerHTML = "";
return;
}
// Debounce: wait 300ms after user stops typing
this.debounceTimer = setTimeout(() => {
this.fetchSuggestions(query);
}, 300);
}
async fetchSuggestions(query) {
try {
const response = await fetch(
`https://sabdasakha.com/api/v1/dictionary/suggest?q=${encodeURIComponent(query)}`
);
const data = await response.json();
this.renderSuggestions(data.root);
} catch (error) {
console.error("Autocomplete error:", error);
}
}
renderSuggestions(suggestions) {
this.container.innerHTML = suggestions
.map(word => `<div class="suggestion" data-word="${word}">${word}</div>`)
.join("");
// Add click handlers
this.container.querySelectorAll(".suggestion").forEach(el => {
el.addEventListener("click", () => {
this.input.value = el.dataset.word;
this.container.innerHTML = "";
});
});
}
}
// Usage
const autocomplete = new NepaliAutocomplete(
document.getElementById("search-input"),
document.getElementById("suggestions")
);
from flask import Flask, render_template, jsonify, request
import requests
app = Flask(__name__)
@app.route("/suggest")
def suggest():
query = request.args.get("q", "")
if len(query) < 2:
return jsonify({"suggestions": []})
response = requests.get(
"https://sabdasakha.com/api/v1/dictionary/suggest",
params={"q": query}
)
data = response.json()
return jsonify({"suggestions": data.get("root", [])})
Real-time Spellcheck Editor
Build a text editor with live spellchecking:
class SpellcheckEditor {
constructor(textareaId, errorsContainerId) {
this.textarea = document.getElementById(textareaId);
this.errorsContainer = document.getElementById(errorsContainerId);
this.debounceTimer = null;
this.errors = [];
this.textarea.addEventListener("input", () => this.onInput());
}
onInput() {
clearTimeout(this.debounceTimer);
// Debounce: check spelling 500ms after user stops typing
this.debounceTimer = setTimeout(() => {
this.checkSpelling();
}, 500);
}
async checkSpelling() {
const text = this.textarea.value;
if (!text.trim()) {
this.errorsContainer.innerHTML = "";
return;
}
try {
const response = await fetch(
"https://sabdasakha.com/api/v1/spellcheck/text",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text })
}
);
const result = await response.json();
this.errors = result.misspelled;
this.renderErrors();
} catch (error) {
console.error("Spellcheck error:", error);
}
}
renderErrors() {
if (this.errors.length === 0) {
this.errorsContainer.innerHTML = '<div class="success">No spelling errors found!</div>';
return;
}
this.errorsContainer.innerHTML = this.errors
.map(error => `
<div class="error">
<span class="word">${error.word}</span>
<span class="suggestions">
${error.suggestions.slice(0, 3).map(s =>
`<button onclick="replaceWord('${error.word}', '${s}')">${s}</button>`
).join(" ")}
</span>
</div>
`)
.join("");
}
}
function replaceWord(oldWord, newWord) {
const textarea = document.getElementById("editor");
textarea.value = textarea.value.replace(oldWord, newWord);
// Trigger re-check
textarea.dispatchEvent(new Event("input"));
}
// Usage
const editor = new SpellcheckEditor("editor", "errors");
Batch Processing
Process multiple words or texts efficiently:
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
def lookup_words_batch(words, max_workers=5):
"""
Look up multiple words concurrently.
Respects rate limits with limited workers.
"""
results = {}
def lookup_single(word):
response = requests.get(
f"https://sabdasakha.com/api/v1/dictionary/word/{word}"
)
return word, response.json() if response.ok else None
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(lookup_single, word): word for word in words}
for future in as_completed(futures):
word, result = future.result()
results[word] = result
return results
# Usage
words = ["नेपाल", "भारत", "चीन", "जापान", "अमेरिका"]
definitions = lookup_words_batch(words)
for word, data in definitions.items():
if data:
print(f"{word}: {data['definitions'][0]}")
else:
print(f"{word}: Not found")
Word of the Day Bot
Create a Twitter/Discord bot that posts a word of the day:
import requests
from datetime import datetime
def get_word_of_the_day():
"""Fetch a random word with its definition and example."""
# Get random example sentence
vakya_response = requests.post(
"https://sabdasakha.com/api/v1/dictionary/vakya/random",
json={"limit": 1}
)
vakya = vakya_response.json()["sentences"][0]
word = vakya["word"]
# Get definition
word_response = requests.get(
f"https://sabdasakha.com/api/v1/dictionary/word/{word}"
)
definition = word_response.json()
return {
"word": word,
"definitions": definition["definitions"],
"part_of_speech": definition.get("part_of_speech", ""),
"example": vakya["sentence"]
}
def format_wotd_message(wotd):
"""Format word of the day for social media."""
date = datetime.now().strftime("%Y-%m-%d")
message = f"""
Word of the Day ({date})
{wotd['word']} ({wotd['part_of_speech']})
Meaning: {', '.join(wotd['definitions'][:2])}
Example: {wotd['example']}
#Nepali #LearnNepali #WordOfTheDay
"""
return message.strip()
# Usage
wotd = get_word_of_the_day()
message = format_wotd_message(wotd)
print(message)
# Post to Twitter/Discord/etc.
# post_to_twitter(message)
Simple Python SDK
Wrap the API in a reusable class:
import requests
from functools import lru_cache
class SabdasakhaClient:
"""Simple SDK for the Sabdasakha API."""
BASE_URL = "https://sabdasakha.com/api/v1"
def __init__(self, timeout=10):
self.timeout = timeout
self.session = requests.Session()
@lru_cache(maxsize=1000)
def lookup(self, word):
"""Look up a word definition (cached)."""
response = self.session.get(
f"{self.BASE_URL}/dictionary/word/{word}",
timeout=self.timeout
)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
return None
else:
response.raise_for_status()
def suggest(self, partial_word):
"""Get autocomplete suggestions."""
response = self.session.get(
f"{self.BASE_URL}/dictionary/suggest",
params={"q": partial_word},
timeout=self.timeout
)
return response.json().get("root", [])
def spellcheck(self, text):
"""Check spelling of text."""
response = self.session.post(
f"{self.BASE_URL}/spellcheck/text",
json={"text": text},
timeout=self.timeout
)
return response.json()
def get_examples(self, word):
"""Get example sentences for a word."""
response = self.session.get(
f"{self.BASE_URL}/dictionary/vakya",
params={"q": word},
timeout=self.timeout
)
return response.json().get("example_sentences", [])
def random_sentences(self, limit=2):
"""Get random example sentences."""
response = self.session.post(
f"{self.BASE_URL}/dictionary/vakya/random",
json={"limit": limit},
timeout=self.timeout
)
return response.json().get("sentences", [])
# Usage
client = SabdasakhaClient()
# Dictionary lookup
result = client.lookup("किताब")
print(result["definitions"])
# Spellcheck
errors = client.spellcheck("नेपाल सुन्दर देस हो")
for error in errors["misspelled"]:
print(f"{error['word']} → {error['suggestions']}")