Using the Wikipedia search API with JavaScript

Recently while working on a website I needed to get accurate search results from Wikipedia. Luckily it has a public API that make this very easy. I used Javascript to fetch data from the API, providing a search term.

First off, I needed an element in the HTML to output the final result to:

<p>More on this author at Wikipedia: <br><a href="" id="wikiLink"><br><span id="wikiLinkText">Text</span><br></a><br></p>

Here I create a link and a span with a unique ID that I will use to output the result.

Next is the JavaScript function itself. In this example I am giving it the search term “Albert Camus”

var term = 'Albert Camus';

var termText = document.getElementById('wikiLinkText');
var wdata = '';
async function showContent() {
   var url = 'https://en.wikipedia.org/w/api.php?' + 
            'action=opensearch' +
            '&search=' + term +
            '&format=json' +
            '&origin=*';
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    var termLink = document.getElementById('wikiLink');
    
    termLink.href = data[3][0];

    wikiLinkText.innerHTML = data[3][0];
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
showContent();

This code will return an array of the search results for ‘Albert Camus’. The link to each article is stored in the third item of the Array, so I am returning the top listed link from the third item of the array. I am then outputing that link to the href and html content.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment Rules

  • No rude or lascivious behavior will be tolerated.
  • Beans contain the souls of the dead - do not eat them.
  • All the other obvious ones.