Building a Dictionary Search
Building a search experience for a dictionary requires handling typos, partial matches, and returning the most relevant results. The Shobdo Search API is designed specifically for linguistic search.
In this guide, we'll walk through how to implement a search bar that fetches real-time dictionary definitions.
The Goal
We want to build a search interface where a user can type a word (e.g., "aple") and we return the correct dictionary entry ("apple").
Step 1: The Search Request
We will use the /api/v1/api/search endpoint. This endpoint takes a q parameter (the search query) and returns an array of matching SearchResult objects wrapped in a standard ApiResponse.
It automatically handles typo-tolerance (fuzzy matching), so a search for "aple" will successfully match "apple".
const searchDictionary = async (query) => {
const response = await fetch(`https://api.shobdo.me/api/v1/api/search?q=${encodeURIComponent(query)}`, {
method: "GET",
headers: {
"Authorization": "Bearer YOUR_API_KEY",
"Accept": "application/json"
}
});
if (!response.ok) {
throw new Error("Failed to fetch search results");
}
const result = await response.json();
return result.data; // Returns an array of SearchResult objects
};Step 2: Parsing the Results
The /search endpoint returns a list of results, ordered by relevance. The first result is almost always the exact match or the closest typo-corrected match.
Let's write a function to extract just the definitions from the top result:
const printTopResult = async (query) => {
const results = await searchDictionary(query);
if (results.length === 0) {
console.log("No results found.");
return;
}
// Grab the top match
const topResult = results[0];
console.log(`Best Match: ${topResult.word} (${topResult.partOfSpeech})`);
console.log(`Preview: ${topResult.preview}`);
if (topResult.hasAudio) {
console.log("Audio is available for this word!");
}
};Since the /search endpoint returns lightweight SearchResult objects optimized for lists, you can then fetch the full HTML definitions by passing topResult.dictionaryId and topResult.id to the /entry/{source}/{id} endpoint.
Step 3: Handling Errors
When building a search experience, it's critical to handle cases where a word doesn't exist.
The /search endpoint will return a 404 Not Found if absolutely no matches (not even fuzzy matches) are found.
try {
await printTopResult("supercalifragilisticexpialidocious");
} catch (error) {
// If the API returns a 404, the fetch request above will throw
console.error("Sorry, we couldn't find that word in our dictionary.");
}Next Steps
Now that you know how to search for full dictionary entries, you might want to optimize your search bar's responsiveness. Check out the Implementing Autocomplete guide to learn how to fetch lightweight type-ahead suggestions as the user types!