Home > Mobile >  How can I use Free Dictionary API to get the top definition of a word?
How can I use Free Dictionary API to get the top definition of a word?

Time:03-13

I've been trying to make a program that spits out the definitions of a word list for a project. I am using https://dictionaryapi.dev/. I've never worked with web apis before, so can I get some help with this.

I've tried var data = $.getJSON("https://api.dictionaryapi.dev/api/v2/entries/en/hello") then document.getElementById('output').innerHTML = data.meanings[1].definition but it doesn't work. It says it can't find what meanings is.

CodePudding user response:

You could use flatMap to retrieve just the definitions from the response:

const DICTIONARY_API_BASE_URL =
    'https://api.dictionaryapi.dev/api/v2/entries/en/';
const DEFINITIONS_DIV = document.getElementById('definitions');

const fetchWordDefinitions = async word => {
    console.log(`Making request for definitions of ${word}...`);
    const response = await fetch(DICTIONARY_API_BASE_URL   word);
    const json = await response.json();
    return json[0].meanings
        .flatMap(m => m.definitions)
        .flatMap(d => d.definition);
};

const getWordDefinitions = () => {
    const word = document.getElementById('word').value;
    if (word == null || word == '') {
        return alert('Error: You must enter a word to fetch');
    }
    DEFINITIONS_DIV.innerHTML = '';
    fetchWordDefinitions(word)
        .then(defintions => {
            defintions.forEach(d => {
                DEFINITIONS_DIV.innerHTML  = `<p>${d}</p>`;
            });
        })
        .catch(_ => {
            DEFINITIONS_DIV.innerHTML  = `<p>Error: Could not retrive any defintions for ${word}.</p>`;
        });
};
* {
  font-family: sans-serif
}
<!DOCTYPE html>
<html>
    <body>
        <h1>Fetch the definitions for a word!</h1>
        <input type="text" id="word" name="word">
        <input type="button" value="Fetch" onClick="getWordDefinitions()">
        <div id="definitions"></div>
    </body>
</html>

  • Related