API Documentation
- API Documentation
- Introduction
The MediaWiki API (Application Programming Interface) is a powerful tool that allows developers to interact with a MediaWiki installation programmatically. Instead of relying solely on the web interface for tasks like editing pages, retrieving content, or managing users, the API provides a standardized way to perform these actions using code. This article provides a comprehensive introduction to the MediaWiki API for beginners, covering its core concepts, common use cases, authentication methods, and essential resources for further learning. Understanding the API opens up possibilities for creating bots, tools, integrations, and customized workflows that significantly extend the functionality of your wiki. This is particularly useful for large wikis with complex data management requirements, or for integrating wiki content with external applications.
- What is an API?
An API, in its simplest form, is a set of rules and specifications that software programs can follow to communicate with each other. Think of it as a contract between two pieces of software. It defines the methods and data formats that applications can use to request and exchange information. In the context of MediaWiki, the API allows external applications to "talk to" the wiki server, request data, and make changes without needing to directly interact with the database.
- Why Use the MediaWiki API?
There are numerous reasons to utilize the MediaWiki API:
- **Automation:** Automate repetitive tasks such as page creation, categorization, and link checking.
- **Data Extraction:** Extract specific data from the wiki for analysis, reporting, or integration with other systems. This data can include everything from article content and revision history to user information and category memberships.
- **Custom Tools:** Develop custom tools and interfaces for managing wiki content, tailored to specific needs.
- **Bot Development:** Create bots to perform automated tasks like vandalism detection, article maintenance, and user interaction. Bots are a crucial part of maintaining large wikis.
- **Integration:** Integrate the wiki with external applications, such as content management systems, forums, or data visualization tools.
- **Scalability:** Handle large-scale data manipulation and updates more efficiently than manual methods.
- **Extensibility:** Extend the functionality of the wiki beyond the standard features provided by the web interface.
- Core Concepts
Before diving into the specifics, let's define some key concepts:
- **Actions:** These are the specific tasks you can perform through the API. Examples include `query` (for retrieving data), `edit` (for modifying pages), `login` (for authenticating users), and `delete` (for deleting pages). Each action has its own set of parameters.
- **Parameters:** These are the data you send to the API along with an action to specify what you want to do and how. Parameters are typically passed as key-value pairs in the URL or as part of the POST data. For example, the `query` action requires parameters like `list` (specifying what type of data to retrieve) and `q` (specifying the search query).
- **Modules:** Within an action, modules specify further refinement of the data requested. For the `query` action, modules like `categories`, `images`, `recentchanges`, and `userinfo` allow you to target specific types of information.
- **Formats:** The API supports various output formats, including JSON, XML, and PHP. JSON is the most commonly used format due to its simplicity and readability.
- **API Endpoint:** The base URL for accessing the MediaWiki API. This is typically `https://yourwiki.com/w/api.php`.
- **Tokens:** Security mechanisms used to authenticate requests and prevent unauthorized access. Different types of tokens are used for different purposes, such as editing and user management. Security is vital when working with APIs.
- Authentication
Accessing certain API actions, particularly those that modify wiki content, requires authentication. MediaWiki offers several authentication methods:
- **User/Password Authentication:** The simplest method, but less secure. Requires sending the username and password with each request. This is generally discouraged in favor of more secure methods.
- **Cookies:** If you are already logged in to the wiki through the web interface, the API can use your existing cookies for authentication. This is the easiest method when working from a web browser.
- **API Tokens:** The most secure and recommended method. API tokens are generated by the wiki and are specific to a user account. They can be used to perform actions on behalf of that user without requiring the password.
* **User Tokens:** Used for actions that require user privileges, such as editing pages. * **CSRF Tokens:** Used to prevent Cross-Site Request Forgery attacks. Required for most POST requests. * **Anon Tokens:** Used for anonymous users. Limited functionality.
To obtain an API token, you can use the `token` action:
``` https://yourwiki.com/w/api.php?action=token&type=user&format=json ```
This will return a JSON response containing the token value. You can then include this token in subsequent API requests.
- Common API Actions
Here are some of the most commonly used API actions:
- **`query`:** The most versatile action for retrieving data from the wiki. You can use it to search for pages, retrieve page content, get category information, list recent changes, and much more. It's the workhorse of the API. See also Data retrieval techniques.
- **`edit`:** Used to create or modify pages. Requires authentication and a valid edit token.
- **`login`:** Used to log in to the wiki. Returns a cookie that can be used for subsequent requests.
- **`logout`:** Used to log out of the wiki.
- **`delete`:** Used to delete pages. Requires authentication and appropriate permissions.
- **`upload`:** Used to upload files to the wiki. Requires authentication and a valid upload token.
- **`categories`:** Used to retrieve a list of categories.
- **`images`:** Used to retrieve information about images.
- **`search`:** Used to search for pages based on keywords.
- **`revisions`:** Used to retrieve revision history of a page.
- **`info`**: Used to retrieve information about the wiki, such as the current version and installed extensions.
- Making API Requests
API requests are typically made using HTTP GET or POST methods.
- GET Requests:** Used for retrieving data. Parameters are passed in the URL as key-value pairs. Example:
``` https://yourwiki.com/w/api.php?action=query&list=search&srsearch=MediaWiki&format=json ```
- POST Requests:** Used for modifying data (e.g., editing pages, uploading files). Parameters are passed in the request body. POST requests generally require a CSRF token for security. You'll need to use a programming language or tool that supports sending POST requests.
- Example: Retrieving Page Content
Here's an example of how to retrieve the content of the "Main Page" using the `query` action and JSON format:
``` https://yourwiki.com/w/api.php?action=query&prop=content&titles=Main Page&format=json ```
The response will be a JSON object containing the page content. You can then parse this JSON object using a programming language like Python, PHP, or JavaScript to extract the content. Understanding JSON parsing is essential.
- Example: Editing a Page
This example demonstrates how to edit a page using the `edit` action (requires authentication and tokens). This is a simplified example and assumes you have already obtained a user token and CSRF token.
``` POST https://yourwiki.com/w/api.php Content-Type: application/x-www-form-urlencoded
action=edit title=Main Page text=This is the new content of the Main Page. summary=Updated content via API token=<your_edit_token> ```
Replace `<your_edit_token>` with your actual edit token. The `summary` parameter is a brief description of the changes you are making.
- Tools and Resources
- **MediaWiki API Documentation:** The official documentation for the MediaWiki API: [1](https://www.mediawiki.org/wiki/API:Main_page)
- **Action API:** A comprehensive list of all available API actions: [2](https://www.mediawiki.org/wiki/API:Actions)
- **Help:API:** A helpful page within MediaWiki itself: [3](https://en.wikipedia.org/wiki/Help:API) (replace `en.wikipedia.org` with your wiki's domain)
- **MediaWiki API Clients:** Libraries and tools for interacting with the API in various programming languages (e.g., Python, PHP, JavaScript).
- **Postman:** A popular tool for testing API requests: [4](https://www.postman.com/)
- **cURL:** A command-line tool for making HTTP requests: [5](https://curl.se/)
- Advanced Topics
- **Rate Limiting:** The API is subject to rate limits to prevent abuse. Be mindful of these limits and implement appropriate throttling mechanisms in your applications.
- **Error Handling:** The API returns error codes and messages when requests fail. Implement robust error handling in your code to gracefully handle these errors.
- **Webhooks:** Configure webhooks to receive notifications when specific events occur in the wiki (e.g., page creation, page deletion).
- **OAuth 2.0:** A more modern and secure authentication protocol that can be used with the MediaWiki API.
- **Using the `feed` action:** Retrieve RSS and Atom feeds for recent changes, watchlist updates, and category contents.
- **Working with Templates:** Manipulating templates programmatically can be complex but powerful. Understanding Templates is crucial.
- **Using `diff`:** Getting the differences between revisions of a page.
- Strategies for Efficient API Usage
- **Caching:** Cache frequently accessed data to reduce the number of API requests.
- **Batching:** Combine multiple requests into a single request whenever possible.
- **Filtering:** Use filters to retrieve only the data you need.
- **Compression:** Enable compression to reduce the size of API responses.
- **Asynchronous Requests:** Use asynchronous requests to avoid blocking your application.
- **Monitor API Usage:** Track your API usage to identify potential bottlenecks and optimize your code.
- **Consider Technical Analysis:** When extracting data for trends, consider using technical analysis indicators like Moving Averages ([6](https://www.investopedia.com/terms/m/movingaverage.asp)), RSI ([7](https://www.investopedia.com/terms/r/rsi.asp)), and MACD ([8](https://www.investopedia.com/terms/m/macd.asp)).
- **Trend Identification:** Employ trend-following strategies like the 200-day moving average ([9](https://school.stockcharts.com/d/p/200DMA)) to understand the overall direction of data changes.
- **Support and Resistance Levels:** Analyze data for support and resistance levels ([10](https://www.investopedia.com/terms/s/supportandresistance.asp)) to identify potential turning points.
- **Fibonacci Retracements:** Utilize Fibonacci retracements ([11](https://www.investopedia.com/terms/f/fibonacciretracement.asp)) to predict potential price or data reversals.
- **Bollinger Bands:** Apply Bollinger Bands ([12](https://www.investopedia.com/terms/b/bollingerbands.asp)) to measure volatility and identify potential breakouts.
- **Elliott Wave Theory:** Explore Elliott Wave Theory ([13](https://www.investopedia.com/terms/e/elliottwavetheory.asp)) for pattern recognition in data trends.
- **Candlestick Patterns:** Recognize candlestick patterns ([14](https://www.investopedia.com/terms/c/candlestick.asp)) for short-term trading signals.
- **Volume Analysis:** Incorporate volume analysis ([15](https://www.investopedia.com/terms/v/volume.asp)) to confirm price trends.
- **Ichimoku Cloud:** Utilize the Ichimoku Cloud ([16](https://www.investopedia.com/terms/i/ichimoku-cloud.asp)) for a comprehensive view of support, resistance, and trend direction.
- **Parabolic SAR:** Employ Parabolic SAR ([17](https://www.investopedia.com/terms/p/parabolicsar.asp)) to identify potential trend reversals.
- **Average True Range (ATR):** Use ATR ([18](https://www.investopedia.com/terms/a/atr.asp)) to measure volatility.
- **Commodity Channel Index (CCI):** Apply CCI ([19](https://www.investopedia.com/terms/c/cci.asp)) to identify overbought and oversold conditions.
- **Donchian Channels:** Utilize Donchian Channels ([20](https://www.investopedia.com/terms/d/donchianchannel.asp)) to identify breakout opportunities.
- **Keltner Channels:** Apply Keltner Channels ([21](https://www.investopedia.com/terms/k/keltnerchannels.asp)) to measure volatility around a moving average.
- **Stochastic Oscillator:** Employ the Stochastic Oscillator ([22](https://www.investopedia.com/terms/s/stochasticoscillator.asp)) to identify potential turning points.
- **Williams %R:** Use Williams %R ([23](https://www.investopedia.com/terms/w/williamspro.asp)) to identify overbought and oversold conditions.
- **Chaikin Money Flow:** Apply Chaikin Money Flow ([24](https://www.investopedia.com/terms/c/chaikinmoneyflow.asp)) to measure buying and selling pressure.
- **On Balance Volume (OBV):** Utilize OBV ([25](https://www.investopedia.com/terms/o/obv.asp)) to confirm price trends.
- **Accumulation/Distribution Line:** Apply the Accumulation/Distribution Line ([26](https://www.investopedia.com/terms/a/accumulationdistributionline.asp)) to measure buying and selling pressure.
- **Heikin Ashi:** Use Heikin Ashi ([27](https://www.investopedia.com/terms/h/heikin-ashi.asp)) charts to smooth price action and identify trends.
- Conclusion
The MediaWiki API is a powerful tool for automating tasks, extracting data, and extending the functionality of your wiki. While it may seem complex at first, understanding the core concepts and utilizing the available resources will enable you to leverage its full potential. Remember to prioritize security, handle errors gracefully, and optimize your code for efficiency. With practice and experimentation, you can unlock a world of possibilities for your MediaWiki installation. API development is a valuable skill for any MediaWiki administrator or developer.
Main Page Help:Contents Manual:Configuration Extension:API MediaWiki User:Example Talk:Main Page Special:AllPages Special:Search Help:Editing