|

|  How to Access Wikipedia Content with MediaWiki API in JavaScript

How to Access Wikipedia Content with MediaWiki API in JavaScript

October 31, 2024

Learn to access Wikipedia content using MediaWiki API in JavaScript. This guide offers step-by-step instructions for efficient data retrieval.

How to Access Wikipedia Content with MediaWiki API in JavaScript

 

Set Up the Environment

 

  • Ensure you have a modern web browser that supports JavaScript and the Fetch API, as these will be crucial for interacting with MediaWiki's API.
  •  

  • You can use any text editor or integrated development environment (IDE) to write your JavaScript code. Popular choices include Visual Studio Code, Sublime Text, or Atom.

 

Understand MediaWiki API Basics

 

  • MediaWiki API is a web service that allows access to wiki features like page content, editing, and user account management.
  •  

  • API requests are made via HTTP and can return data in various formats, mainly JSON, which is easy to use with JavaScript.
  •  

  • You'll interact with endpoints using RESTful principles and specify actions through URL query parameters.

 

Fetch Content from Wikipedia

 

  • Start with a basic JavaScript function to fetch articles. Use the `fetch` function which is part of the Fetch API to carry out network requests.
  •  

  • To access the content of a Wikipedia article, you'll need to specify the action as "query" and provide the title of the article. Here’s a basic example function:
async function fetchWikipediaArticle(title) {
    const response = await fetch(`https://en.wikipedia.org/w/api.php?action=query&format=json&origin=*&titles=${encodeURIComponent(title)}&prop=extracts&explaintext`);
    const data = await response.json();
    const pages = data.query.pages;
    const pageId = Object.keys(pages)[0];
    return pages[pageId].extract;
}

fetchWikipediaArticle("JavaScript")
    .then(extract => console.log(extract))
    .catch(error => console.log('Error:', error));
  • The `origin=*` parameter is necessary to avoid CORS issues when making requests from a web browser.
  •  

  • The `extracts` property and `explaintext` parameter are used to retrieve plain text content without HTML formatting.

 

Handle Different Content Outputs

 

  • MediaWiki API doesn't just provide plain text. You can request HTML content or structured data for more robust applications:
  •  

  • Modify the `prop` field in your query to get different types of content. For HTML content:
async function fetchWikipediaHtml(title) {
    const response = await fetch(`https://en.wikipedia.org/w/api.php?action=parse&format=json&origin=*&page=${encodeURIComponent(title)}&prop=text`);
    const data = await response.json();
    return data.parse.text['*'];
}
  • Now, `fetchWikipediaHtml` retrieves the article's content as formatted HTML.
  •  

  • You can dynamically inject this HTML into your web application's DOM if necessary.

 

Deal with API Limits and Errors

 

  • Keep in mind that Wikipedia imposes request limits to prevent abuse. Implement mechanisms to handle such situations gracefully.
  •  

  • Error handling can be incorporated into your functions using try-catch blocks. Log errors or notify the user as appropriate.

 

Additional Features to Explore

 

  • Explore additional API endpoints like `action=opensearch` for search suggestions or `action=query&list=categories` to fetch categories for articles.
  •  

  • Integrate the API calls with front-end frameworks like React or Vue.js for a more comprehensive user interface experience.

 

Use Asynchronous Programming Practices

 

  • Maximize the use of async/await, Promises, and other asynchronous coding practices to make non-blocking API calls and provide a smooth user experience.
  •  

  • Consider implementing paging or infinite scroll techniques when working with large datasets provided by the API.

 

Pre-order Friend AI Necklace

Pre-Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Perfect for developers and tech enthusiasts who want to start creating immediately.

Has 64gb of on-board memory, a speaker, vibration and a programmable button.

Comes fully assembled, doesn't require technical skills to set up.

 

IMPORTANT: On backorder. Shipping end of November 2024.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

San Francisco

team@basedhardware.com
Title

Company

About

Careers

Invest
Title

Products

Omi Dev Kit 2

Openglass

Other

App marketplace

Affiliate

Privacy

Customizations

Discord

Docs

Help