DEV Community

Cover image for How to use Free dictionary API
Iryna Trush
Iryna Trush

Posted on • Edited on

5

How to use Free dictionary API

Cover photo by Christopher Gower on Unsplash

The Free Dictionary API is a powerful tool that enables developers to easily integrate lexical data into their projects. It provides access to a comprehensive collection of English word definitions, phonetic transcriptions, and related linguistic information.

Whether you're building a language learning application, enhancing a spell-checking feature, or requiring dictionary data for any other purpose, the Free Dictionary API offers a straightforward solution for retrieving and utilizing this valuable resource.


In this API documentation:


Overview:

Developed by meetDeveloper and reaching 2.6k stars on GitHub, the Free Dictionary API offers a simple way to integrate dictionary data into your applications.


Note: API supports only GET requests.

Key Features:

  • Free to use
  • No usage limits
  • No authorization or API keys required

Endpoint

https://api.dictionaryapi.dev/api/v2/entries/en/<word>
Enter fullscreen mode Exit fullscreen mode
  • This endpoint retrieves dictionary information for the specified English word.

  • The API has two versions: v1 and v2. The primary difference lies in the response structure. Current version is v2.

Query Parameters

  • word (string, required): The word you want to look up.

Response Format

The API returns a JSON array containing a single object with detailed information about the word, including:

If the request is successful:

  • word (string): The queried word.
  • phonetic (string): The phonetic transcription of the word.
  • phonetics (array): An array of phonetic objects, each with:
    • text (string): The phonetic transcription.
    • audio (string): A URL to an audio pronunciation (may be empty).
  • meanings (array): An array of objects representing different meanings of the word, each with:
    • partOfSpeech (string): The part of speech (e.g., noun, verb).
    • definitions (array): An array of definition objects, each with:
    • definition (string): The definition of the word.
    • synonyms (array): An array of synonyms.
    • antonyms (array): An array of antonyms.
  • license (object): Information about the license under which the data is provided.
  • sourceUrls (array): An array of URLs to the sources of the data.

If the request is not successful:

  • title (string): A message indicating that no definitions were found for the word
  • message (string): Message that the definitions for the word was not found
  • resolution(string): Suggestion to use search again or web.

Examples:

Example Request 1 (successful):

const word = "documentation";
fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
  .then(response => response.json())
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

Example Response 1:

[
  {
    "word": "documentation",
    "phonetic": "/ˌdɒkjʊmənˈteɪʃən/",
    "phonetics": [
      {
        "text": "/ˌdɒkjʊmənˈteɪʃən/",
        "audio": ""
      },
      {
        "text": "/ˌdɑkjəmənˈteɪʃən/",
        "audio": ""
      }
    ],
    "meanings": [
      {
        "partOfSpeech": "noun",
        "definitions": [
          {
            "definition": "Something transposed from a thought to a document; the written account of an idea.",
            "synonyms": [],
            "antonyms": []
          },
          {
            "definition": "Documentary evidence and sources.",
            "synonyms": [],
            "antonyms": []
          },
          {
            "definition": "Documents that explain the operation of a particular machine or software program.",
            "synonyms": [],
            "antonyms": []
          },
          {
            "definition": "Comments that explain the usage of individual functions, libraries and blocks of code.",
            "synonyms": [],
            "antonyms": []
          }
        ],
        "synonyms": [],
        "antonyms": []
      }
    ],
    "license": {
      "name": "CC BY-SA 3.0",
      "url": "https://creativecommons.org/licenses/by-sa/3.0"
    },
    "sourceUrls": [
      "https://en.wiktionary.org/wiki/documentation"
    ]
  }
]
Enter fullscreen mode Exit fullscreen mode

Example Request 2 :

const word = "Software engineer";
fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
  .then(response => response.json())
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

Example Response 2 (not successful):

{
  "title": "No Definitions Found",
  "message": "Sorry pal, we couldn't find definitions for the word you were looking for.",
  "resolution": "You can try the search again at later time or head to the web instead."
}
Enter fullscreen mode Exit fullscreen mode

Success and Error codes

This API does not currently return specific success or error codes.


Code it up

Now that you understand how to use an API, it's time for practice.

Let's build a simple dictionary lookup web application using HTML, CSS, and JavaScript. This application will allow users to enter a word into a search bar, click a button, and see the word's definition.


First, we'll create the HTML structure. We'll need an input field for the user to enter the word, a button to trigger the search, and a <div> to display the results.

      <input
        type="text"
        id="input"
        class="search-input"
        placeholder="Enter a word"
        aria-label="Enter a word to look up"
      />
      <button id="btn" class="btn" aria-label="Look up the word">
        Look up
      </button>
      <div id="result" class="result"></div>
    </div>

Enter fullscreen mode Exit fullscreen mode

Next, we will write the JavaScript code to handle the user input, fetch the word meaning from the Free Dictionary API, and display the results:

We'll start by getting references to the HTML elements using
document.getElementById:

const btn = document.getElementById("btn");
const wordInput = document.getElementById("input");
const displayResultDiv = document.getElementById("result");

Enter fullscreen mode Exit fullscreen mode

Next step - add an event listener to the button to handle the click event. When the button is clicked, we'll retrieve the word entered by the user and call the getMeaning function.

btn.addEventListener("click", () => {
  const word = wordInput.value.trim();
  if (word) {
    getMeaning(word);
  } else {
    displayResultDiv.textContent = "Please enter a word.";
  }
});
Enter fullscreen mode Exit fullscreen mode

Now, let's implement the getMeaning function to fetch the definition from the Free Dictionary API:

const getMeaning = async (word) => {
  try {
    const response = await fetch(
      `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`
    );
    if (!response.ok) {
      throw new Error("Sorry. Word not found");
    }
    const data = await response.json();
    displayMeaning(data);
  } catch (error) {
    displayResultDiv.textContent = error.message;
  } finally {
    wordInput.value = "";
  }
};

Enter fullscreen mode Exit fullscreen mode

This function fetches the word's definition from the API. If the word is found, it calls the displayMeaning function to display the results. If an error occurs (e.g., the word isn't found), it displays an error message. The finally block clears the input field after the search, regardless of success or failure.


Finally, let's create the displayMeaning function to format and display the definition:

const displayMeaning = (data) => {
  const wordData = data[0];
  const phonetics = wordData.phonetics
    .map(
      (p) =>
        `<div class="result-item">${p.text} <audio class="result-audio" controls src="${p.audio}"></audio></div>`
    )
    .join("");
  const meanings = wordData.meanings
    .map((meaning) => {
      const definitions = meaning.definitions
        .map((def) => `<li>${def.definition}</li>`)
        .join("");
      return `<div class="result-item"><strong>${meaning.partOfSpeech}</strong><ul>${definitions}</ul></div>`;
    })
    .join("");

  displayResultDiv.innerHTML = `
    <h2 class="result-title">${wordData.word}</h2>
    <div>${phonetics}</div>
    <div>${meanings}</div>
    <div class="result-item"><a href="${wordData.sourceUrls[0]}" target="_blank">Source</a></div>
  `;
};

Enter fullscreen mode Exit fullscreen mode

This function extracts the relevant information from the API response, formats it into HTML, and sets the innerHTML of the displayResultDiv. It handles phonetics (including optional audio) and definitions, and provides a link to the source.


This completes the core functionality of the dictionary lookup application. You can further enhance it with CSS styling and error handling. A complete demo, including CSS, can be found at this link to the project.


Additional resources

To try the API or support the Free Dictionary API, go to Free Dictionary API website.

See also Free Dictionary API project on Github.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more