|

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

 

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit 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 開発キット 2

無限のカスタマイズ

OMI 開発キット 2

$69.99

Omi AIネックレスで会話を音声化、文字起こし、要約。アクションリストやパーソナライズされたフィードバックを提供し、あなたの第二の脳となって考えや感情を語り合います。iOSとAndroidでご利用いただけます。

  • リアルタイムの会話の書き起こしと処理。
  • 行動項目、要約、思い出
  • Omi ペルソナと会話を活用できる何千ものコミュニティ アプリ

もっと詳しく知る

Omi Dev Kit 2: 新しいレベルのビルド

主な仕様

OMI 開発キット

OMI 開発キット 2

マイクロフォン

はい

はい

バッテリー

4日間(250mAH)

2日間(250mAH)

オンボードメモリ(携帯電話なしで動作)

いいえ

はい

スピーカー

いいえ

はい

プログラム可能なボタン

いいえ

はい

配送予定日

-

1週間

人々が言うこと

「記憶を助ける、

コミュニケーション

ビジネス/人生のパートナーと、

アイデアを捉え、解決する

聴覚チャレンジ」

ネイサン・サッズ

「このデバイスがあればいいのに

去年の夏

記録する

「会話」

クリスY.

「ADHDを治して

私を助けてくれた

整頓された。"

デビッド・ナイ

OMIネックレス:開発キット
脳を次のレベルへ

最新ニュース
フォローして最新情報をいち早く入手しましょう

最新ニュース
フォローして最新情報をいち早く入手しましょう

thought to action.

Based Hardware Inc.
81 Lafayette St, San Francisco, CA 94103
team@basedhardware.com / help@omi.me

Company

Careers

Invest

Privacy

Events

Manifesto

Compliance

Products

Omi

Wrist Band

Omi Apps

omi Dev Kit

omiGPT

Personas

Omi Glass

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

Ambassadors

Resellers

© 2025 Based Hardware. All rights reserved.