API documentation
- API Documentation for MediaWiki Beginners
Introduction
The MediaWiki API (Application Programming Interface) is a powerful and versatile tool that allows developers to interact with a MediaWiki installation programmatically. This means that instead of manually using the web interface to edit pages, upload files, or search for content, you can write scripts or applications to do these things automatically. This article is designed for beginners with little to no prior experience with APIs, aiming to provide a comprehensive understanding of the MediaWiki API and how to leverage it. Understanding the API is crucial for extending MediaWiki's functionality, creating bots, and integrating it with other systems. It's a complex topic, but we’ll break it down into manageable sections. Before diving in, it's helpful to understand the core concepts of a client-server model, where your script (the client) requests information or actions from the MediaWiki server.
What is an API?
At its core, an API is a set of rules and specifications that software programs can follow to communicate with each other. Think of it as a contract: it defines what requests a program can make, how to make those requests, and what responses to expect. Without APIs, applications would be isolated silos, unable to share data or functionality.
In the context of MediaWiki, the API provides access to almost all of the features available through the web interface, and more. This includes reading page content, editing pages, uploading files, managing users, searching for data, and much more. The MediaWiki API utilizes a standardized web-based approach, primarily using HTTP requests and responses in formats like JSON and XML.
Why Use the MediaWiki API?
There are numerous reasons why you might want to use the MediaWiki API:
- **Automation:** Automate repetitive tasks, such as updating templates, correcting common errors, or importing data.
- **Bot Development:** Create bots to perform specific functions, like reverting vandalism, adding categories, or monitoring changes. See Bots for more information.
- **Integration:** Integrate MediaWiki with other systems, like external databases, content management systems, or social media platforms.
- **Data Extraction:** Extract data from MediaWiki for analysis or reporting. This is useful for tracking page views, editor activity, or content trends. Consider using Semantic MediaWiki for structured data.
- **Custom Tools:** Build custom tools to enhance the MediaWiki experience for your users.
- **Scalability:** Handle large-scale operations that would be impractical or impossible to perform manually.
Core Concepts of the MediaWiki API
Before you start writing code, it's important to understand the key concepts:
- **Actions:** These are the specific tasks you want to perform, such as `edit`, `query`, `upload`, or `login`. Each action has its own set of parameters.
- **Parameters:** These are the values you pass to the API to specify how you want the action to be performed. For example, the `edit` action requires parameters like `title` (the page to edit), `text` (the new content), and `summary` (the edit summary).
- **Formats:** The API supports different data formats for requests and responses. The most common formats are:
* **JSON (JavaScript Object Notation):** A lightweight and easy-to-parse format, widely used in web applications. Highly recommended for beginners. * **XML (Extensible Markup Language):** A more verbose format, but still widely used.
- **HTTP Methods:** The API uses standard HTTP methods:
* **GET:** Used to retrieve data. * **POST:** Used to submit data, such as editing a page or uploading a file.
- **Authentication:** Many API actions require authentication to prevent unauthorized access. This is typically done using usernames and passwords, or via OAuth for more secure applications.
- **API Endpoint:** The base URL for accessing the MediaWiki API is usually `https://yourwiki.com/w/api.php`. Replace `yourwiki.com` with the actual domain of your MediaWiki installation.
Making Your First API Request
Let's illustrate with a simple example: retrieving the content of the "Main Page" using the `query` action. We'll use Python and the `requests` library (install it with `pip install requests`).
```python import requests
url = "https://yourwiki.com/w/api.php" params = {
"action": "query", "title": "Main Page", "format": "json", "prop": "revisions", "rvprop": "content"
}
response = requests.get(url, params=params) data = response.json()
if 'query' in data and 'pages' in data['query']:
page_id = list(data['query']['pages'].keys())[0] if page_id != "-1": content = data['query']['pages'][page_id]['revisions'][0]['content'] print(content) else: print("Page not found.")
else:
print("Error retrieving page content.")
```
This code does the following:
1. **Imports the `requests` library.** 2. **Defines the API endpoint URL.** 3. **Creates a dictionary of parameters:**
* `action`: Specifies the `query` action. * `title`: Specifies the page title ("Main Page"). * `format`: Specifies the response format (`json`). * `prop`: Specifies the properties to retrieve (`revisions`). * `rvprop`: Specifies the revision properties to retrieve (`content`).
4. **Sends a GET request to the API endpoint with the parameters.** 5. **Parses the JSON response.** 6. **Extracts the page content and prints it.**
Remember to replace `https://yourwiki.com` with the actual URL of your MediaWiki installation.
Common API Actions
Here's a brief overview of some common API actions:
- **`edit`:** Edit a page. Requires parameters like `title`, `text`, and `summary`.
- **`query`:** Retrieve data about pages, users, categories, and more. Highly versatile.
- **`upload`:** Upload a file. Requires parameters like `filename`, `file`, and `comment`.
- **`login`:** Log in a user. Requires parameters like `username` and `password`.
- **`logout`:** Log out a user.
- **`search`:** Search for pages. Requires parameters like `search` and `list`.
- **`categories`:** Retrieve the categories a page belongs to.
- **`images`:** Retrieve information about images.
- **`userinfo`:** Retrieve information about a user.
- **`watchlist`:** Manage a user's watchlist.
Authentication and User Rights
Many API actions require authentication. You can authenticate using:
- **User/Password:** The simplest method, but less secure. Avoid using this in production environments.
- **Cookies:** If you are already logged in through the web interface, you can reuse your session cookie for API requests.
- **OAuth:** The most secure method, allowing applications to access MediaWiki on behalf of a user without knowing their password. OAuth
The permissions required to perform an action depend on the user's rights within the MediaWiki installation. For example, editing a page requires the `edit` permission. You can check a user's rights using the `userinfo` action.
Error Handling
The MediaWiki API returns error codes in the response. It's crucial to handle these errors gracefully in your code. Common error codes include:
- `invalidtitle`: The specified page title is invalid.
- `noeffect`: The requested action had no effect (e.g., trying to edit a page with the same content).
- `permissiondenied`: The user does not have permission to perform the requested action.
- `readonly`: The wiki is in read-only mode.
- `badtoken`: The API token is invalid.
Always check the `error` field in the API response and handle the error appropriately.
Advanced Topics
- **API Modules:** The API is organized into modules, each providing access to a specific set of functionalities.
- **API Limits:** The API has rate limits to prevent abuse. Be mindful of these limits and implement appropriate throttling mechanisms in your code.
- **Webhooks:** Use webhooks to receive notifications when certain events occur in MediaWiki (e.g., a page is edited). Requires extensions.
- **Utilizing `mwclient`:** The `mwclient` Python library provides a more convenient way to interact with the MediaWiki API, abstracting away some of the complexities. See [1](https://mwclient.readthedocs.io/en/latest/)
- **Learning from Existing Bots:** Examine the source code of existing MediaWiki bots to learn best practices and techniques. List of bots
Resources
- **MediaWiki API Documentation:** [2](https://www.mediawiki.org/wiki/API:Main_page)
- **MediaWiki API Tutorials:** [3](https://www.mediawiki.org/wiki/Tutorials/API_usage)
- **Stack Overflow:** [4](https://stackoverflow.com/questions/tagged/mediawiki-api)
- **mwclient Documentation:** [5](https://mwclient.readthedocs.io/en/latest/)
- **Technical Analysis Resources:** [6](https://www.investopedia.com/terms/t/technicalanalysis.asp), [7](https://school.stockcharts.com/doku.php/technical_analysis)
- **Trading Strategies:** [8](https://www.babypips.com/learn-forex/forex-trading-strategies)
- **Candlestick Patterns:** [9](https://www.investopedia.com/terms/c/candlestick.asp)
- **Moving Averages:** [10](https://www.investopedia.com/terms/m/movingaverage.asp)
- **Fibonacci Retracements:** [11](https://www.investopedia.com/terms/f/fibonacciretracement.asp)
- **Bollinger Bands:** [12](https://www.investopedia.com/terms/b/bollingerbands.asp)
- **MACD Indicator:** [13](https://www.investopedia.com/terms/m/macd.asp)
- **RSI Indicator:** [14](https://www.investopedia.com/terms/r/rsi.asp)
- **Trend Lines:** [15](https://www.investopedia.com/terms/t/trendline.asp)
- **Support and Resistance:** [16](https://www.investopedia.com/terms/s/supportandresistance.asp)
- **Elliott Wave Theory:** [17](https://www.investopedia.com/terms/e/elliottwave.asp)
- **Head and Shoulders Pattern:** [18](https://www.investopedia.com/terms/h/headandshoulders.asp)
- **Double Top and Double Bottom:** [19](https://www.investopedia.com/terms/d/doubletop.asp)
- **Chart Patterns:** [20](https://www.investopedia.com/technical-analysis/chart-patterns/)
- **Trading Psychology:** [21](https://www.investopedia.com/terms/t/trading-psychology.asp)
- **Risk Management:** [22](https://www.investopedia.com/terms/r/riskmanagement.asp)
- **Backtesting:** [23](https://www.investopedia.com/terms/b/backtesting.asp)
- **Algorithmic Trading:** [24](https://www.investopedia.com/terms/a/algorithmic-trading.asp)
- **Day Trading:** [25](https://www.investopedia.com/terms/d/daytrading.asp)
- **Swing Trading:** [26](https://www.investopedia.com/terms/s/swingtrading.asp)
- **Position Trading:** [27](https://www.investopedia.com/terms/p/positiontrading.asp)
- **Scalping:** [28](https://www.investopedia.com/terms/s/scalping.asp)
- **Market Sentiment:** [29](https://www.investopedia.com/terms/m/marketsentiment.asp)
Conclusion
The MediaWiki API is a powerful tool that can significantly extend the functionality of your wiki. While it can seem daunting at first, breaking it down into smaller concepts and starting with simple examples can help you get up to speed quickly. Experiment, explore the documentation, and don't be afraid to ask for help from the MediaWiki community. With a little effort, you can unlock the full potential of the MediaWiki API. Extension development often relies heavily on the API. Consider exploring MediaWiki gadgets as a simpler entry point.
Start Trading Now
Sign up at IQ Option (Minimum deposit $10) Open an account at Pocket Option (Minimum deposit $5)
Join Our Community
Subscribe to our Telegram channel @strategybin to receive: ✓ Daily trading signals ✓ Exclusive strategy analysis ✓ Market trend alerts ✓ Educational materials for beginners