Skip to content

MediaWiki REST API — Action API, Query Modules, Authentication, and API Usage

DodaTech Updated 2026-06-26 9 min read

In this tutorial, you will learn about MediaWiki REST API. We cover key concepts, practical examples, and best practices to help you master this topic.

The MediaWiki API is a powerful HTTP interface that lets applications read and write wiki data programmatically — from the Action API for complex operations and query modules to REST endpoints and token-based authentication, the same API ecosystem that Wikipedia exposes to thousands of third-party tools and services.

What You'll Learn

  • Understanding the MediaWiki API architecture
  • Using the Action API for queries and edits
  • Working with REST API endpoints
  • Authenticating with tokens and OAuth
  • Building API-powered applications
  • Following API best practices

Why It Matters

The API is how programs talk to your wiki. Without it, every automated task requires screen scraping. The API provides structured access to everything: read page content, search, list categories, get user information, edit pages, move pages, and upload files. Applications built on the API range from mobile apps to desktop tools to automated scripts. Understanding the API unlocks the full programmatic potential of your wiki.

Real-World Use

A DodaTech mobile app displays wiki documentation for offline reading. The app uses the API to fetch pages, download images, and check for updates. A monitoring dashboard uses the API to show recent changes and wiki statistics. A CI/CD pipeline uses the API to update documentation when code is deployed. All three use the same API with different authentication methods.

Learning Path

flowchart LR
  A["32: Content Translation"] --> B["33: Import & Export"]
  B --> C["34: REST API"]
  C:::current
  D["35: Database Maintenance"]
  E["36: Logging & Monitoring"]
  F["37: Backup & Restore"]

  C --> D --> E --> F

  classDef current fill#38bdf8,color#0f172a,stroke-width:2px

API Architecture

MediaWiki provides two APIs:

  • Action API (api.php): Complete access to all wiki operations
  • REST API (rest.php): Simpler, resource-oriented endpoints for common tasks

API Entry Points

Action API:  https://yourwiki/api.php
REST API:    https://yourwiki/rest.php

Interactive Exploration

Both APIs provide interactive exploration:

https://yourwiki/api.php?action=help       — Action API help
https://yourwiki/rest.php/                 — REST API entry point

The Action API sandbox at Special:ApiSandbox lets you test API calls interactively.

Action API Basics

All Action API calls use the api.php endpoint with format=json for structured responses.

Making a Request

https://yourwiki/api.php?
  action=query&
  titles=Main_Page&
  prop=info&
  format=json

Response:

{
  "batchcomplete": "",
  "query": {
    "pages": {
      "1": {
        "pageid": 1,
        "ns": 0,
        "title": "Main Page",
        "contentmodel": "wikitext",
        "pagelanguage": "en",
        "touched": "2026-06-28T10:00:00Z",
        "lastrevid": 100,
        "length": 500
      }
    }
  }
}

HTTP Methods

  • GET: Read operations (query, list, search)
  • POST: Write operations (edit, delete, upload, move)

Read operations are idempotent. Write operations require authentication tokens.

Querying Page Content

Get Page Content

https://yourwiki/api.php?
  action=query&
  titles=DodaBrowser&
  prop=revisions&
  rvprop=content&
  format=json

Response includes the wikitext content of the latest revision.

Search Pages

https://yourwiki/api.php?
  action=query&
  list=search&
  srsearch=installation&
  srlimit=10&
  format=json

List Categories

https://yourwiki/api.php?
  action=query&
  list=allcategories&
  acprefix=D&
  format=json

Get Page with All Properties

https://yourwiki/api.php?
  action=query&
  titles=DodaBrowser&
  prop=info|revisions|categories|images|links&
  format=json

Authenticated Operations

Writing to the wiki requires authentication.

Step 1: Log In (Bot Password)

import requests

API_URL = 'https://yourwiki/api.php'
session = requests.Session()

# Log in with bot password
login_params = {
    'action': 'login',
    'lgname': 'MyBot',
    'lgpassword': 'MyBot@password_string',
    'format': 'json',
}
session.post(API_URL, data=login_params)

# Get CSRF token
token_params = {
    'action': 'query',
    'meta': 'tokens',
    'type': 'csrf',
    'format': 'json',
}
token_response = session.get(API_URL, params=token_params)
token = token_response.json()['query']['tokens']['csrftoken']

# Edit a page
edit_params = {
    'action': 'edit',
    'title': 'Sandbox',
    'text': 'Hello from API!',
    'summary': 'Testing API edit',
    'token': token,
    'format': 'json',
}
response = session.post(API_URL, data=edit_params)
print(response.json())

Step 2: OAuth

For applications that need access on behalf of users, use OAuth:

# Using mwoauth library
from mwoauth import ConsumerToken, Handshaker
import requests

consumer_token = ConsumerToken('consumer_key', 'consumer_secret')
handshaker = Handshaker('https://yourwiki/w/index.php', consumer_token)

# Redirect user to authorization URL
redirect_url, request_token = handshaker.initiate()

# After user authorizes, complete the handshake
access_token = handshaker.complete(request_token, 'verification_code')

# Make authenticated requests
response = handshaker.request(access_token, {
    'action': 'query',
    'meta': 'userinfo',
    'format': 'json',
})

REST API

The REST API provides simpler, resource-oriented endpoints.

Available Endpoints

GET    /rest.php/v1/page/{title}           — Get page content
GET    /rest.php/v1/page/{title}/html      — Get rendered HTML
PUT    /rest.php/v1/page/{title}           — Create or update page
DELETE /rest.php/v1/page/{title}           — Delete page
GET    /rest.php/v1/search/page?q={query}  — Search pages
GET    /rest.php/v1/user/{name}            — Get user info

Getting Page HTML

import requests

response = requests.get(
    'https://yourwiki/rest.php/v1/page/DodaBrowser/html',
    headers={'Accept': 'text/html'}
)
html_content = response.text

Creating a Page via REST

import requests

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_OAUTH_TOKEN',
}
data = {
    'source': ''''DodaBrowser''' is a web browser.',
    'comment': 'Created via REST API',
}
response = requests.put(
    'https://yourwiki/rest.php/v1/page/NewPage',
    json=data,
    headers=headers,
)

API Modules

prop Modules (Page Properties)

prop=info         — Basic page information
prop=revisions    — Revision content and metadata
prop=categories   — Categories the page belongs to
prop=images       — Images used on the page
prop=templates    — Templates used on the page
prop=links        — Outgoing wikilinks
prop=extlinks     — External links
prop=pageprops    — Page properties (magic words)

list Modules

list=allpages         — List all pages in a namespace
list=allcategories    — List all categories
list=allusers         — List all users
list=recentchanges    — Recent wiki activity
list=search           — Full-text search
list=watchlist        — Current user's watchlist
list=logevents        — Log entries

meta Modules

meta=siteinfo        — Wiki configuration info
meta=tokens         — CSRF and other tokens
meta=userinfo       — Current user information
meta=filerepoinfo   — File repository information

Error Handling

The API returns errors in a structured JSON format:

{
  "error": {
    "code": "missingtitle",
    "info": "The page you requested does not exist",
    "docref": "See https://yourwiki/api.php..."
  }
}

Common Error Codes

Code Meaning
missingtitle Page does not exist
permissiondenied User lacks required rights
badtoken Invalid or expired CSRF token
ratelimited Too many requests
readapidenied Anonymous API access disabled
paramvalidation Invalid or missing parameter

Handling Errors in Python

response = requests.get(API_URL, params=params)
data = response.json()
if 'error' in data:
    print(f"API Error: {data['error']['info']}")
elif 'warnings' in data:
    print(f"Warning: {data['warnings']}")
else:
    print("Success:", data)

API Best Practices

Rate Limiting

import time

for page in pages:
    # Make API request
    response = call_api(page)
    # Wait to avoid rate limiting
    time.sleep(1)

Use Appropriate Formats

  • Use format=json for machine consumption
  • Use format=xml for legacy systems
  • Always specify a format (default is XML)

Minimize Data Transfer

# Good: request only needed data
params = {
    'action': 'query',
    'titles': 'DodaBrowser',
    'prop': 'revisions',
    'rvprop': 'content',     # Only fetch content
    'rvlimit': 1,            # Only latest revision
    'format': 'json',
}

User-Agent Header

Always set a descriptive User-Agent:

headers = {
    'User-Agent': 'DodaTechBot/1.0 (https://dodatech.com; bot@dodatech.com)'
}
response = requests.get(API_URL, params=params, headers=headers)

What You Learned

  • MediaWiki has two APIs: Action API and REST API
  • Action API (api.php) handles all wiki operations
  • Read operations use GET; write operations use POST with tokens
  • Bot passwords provide secure API authentication
  • OAuth enables third-party application access
  • REST API provides simpler resource-oriented endpoints
  • Error handling checks for both errors and warnings
  • Best practices include rate limiting and proper User-Agent headers

In the next lesson, you'll learn about database maintenance.

Common Mistakes

Mistake Why It Happens How to Fix
API returns HTML instead of JSON Missing format=json parameter Always include &format=json in your API requests. Without it, the API returns XML by default.
"badtoken" error on write operations Token was fetched with GET, not POST Fetch CSRF tokens using a POST request. The token must be from the current session.
Edit fails with "permissiondenied" User lacks edit rights or bot password lacks the edit grant Check the bot password grants. Verify the user has edit permission. Check wiki read-only status.
Rate limiting blocks requests Too many requests too quickly Add delays between requests. Use the maxlag parameter to respect server load. Implement exponential backoff on 429 responses.
API URL returns 404 Wrong path to api.php Verify the API path: https://yourwiki/api.php or https://yourwiki/w/api.php. Check that the wiki is installed at the expected path.

Practice Questions

  1. What is the difference between the Action API and REST API?
  2. How do you authenticate an API request for editing a page?
  3. Write a Python script that searches for pages containing "MediaWiki" and returns the titles and page IDs.
  4. Challenge: Build an API-powered application. Write a Python script that: (a) logs in using a bot password, (b) fetches the content of a specified page, (c) counts the number of internal links on the page, (d) lists all categories the page belongs to, (e) creates a new page with a summary report containing the link count and category list, (f) adds a comment to the page. Add rate limiting and proper error handling. Run the script and verify the new page was created with correct content.

FAQ

What is the difference between api.php and rest.php?

api.php (Action API) provides complete access to all wiki features with a uniform parameter interface. rest.php (REST API) provides simpler, resource-oriented endpoints for common tasks. The Action API is more powerful; the REST API is easier to use.

Can I access the API without authentication?

Yes. Read operations (queries, search, listing) are available without authentication if the wiki allows anonymous read access. Write operations require authentication via bot passwords or OAuth.

What is the API sandbox?

Special:ApiSandbox is an interactive tool on your wiki that lets you construct API requests, test them, and see results without writing code. It shows available parameters, generates sample URLs, and formats responses.

How do I handle pagination in API results?

Use the 'continue' parameter. The API returns a 'continue' value when there are more results. Pass this value in your next request to get the next batch of results. Each list module has its own continue parameter.

What is maxlag and how does it work?

maxlag is a parameter that tells the API to wait if the wiki's database replication lag exceeds a threshold. Use maxlag=5 to pause requests when lag exceeds 5 seconds. This prevents you from contributing to server load during peak times.

Mini Project

Goal: Build a Python application that interacts with your wiki through the API.

  1. Create a bot account and generate a bot password
  2. Write a Python script that:
    • Logs in to the wiki using the bot password
    • Fetches the content of the "Main Page"
    • Lists the last 10 recent changes
    • Creates a new page "API Report" containing the recent changes list
    • Verifies the page was created
  3. Add error handling for common API errors
  4. Add rate limiting (1 request per second)
  5. Set a descriptive User-Agent header
  6. Test the script and verify it works correctly
  7. Extend the script to:
    • Accept command-line arguments (page title, edit summary)
    • Support dry-run mode (show what would change without saving)
  8. Document the script and its usage

What's Next

The API opens your wiki to programmatic access. Now let's dive into database maintenance for keeping your wiki healthy.

Continue to Lesson 35: Database Maintenance — learn about maintenance scripts, update.php, and rebuilding indexes.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro