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 makes this very easy. I used JavaScript to fetch data from the API, providing a search term. For this example I have predefined the search term to make it easier, but any string text will be searchable.

First off, I needed an element in the HTML to output the final result to. It consists of a link and some text. Here is the HTML:

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

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”

I am using the JS fetch() functionality to get results from the PHP API, but obviously there are endless possibilities if you need another method. Those using frameworks will likely want to use Axios or some similar library. As always it is an asynchronous function that returns a promise. I am not doing anything with errors other than outputting them to the console.

var term = 'Albert Camus';

var termText = document.getElementById('wikiLinkText');
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();

The API request is simple, but requires a bit of examination. The action is the most loquacious part and can be set to a range of actions, I am using the opensearch protocol to return search result, but there are numerous options available. Format defines the data returned, in this case it will return a Json object. Origin is important as without this you will most likely get a CORS error when the request is online.

More info on the Wikimedia API can be found here: https://www.mediawiki.org/wiki/API:Action_API

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 outputting 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.