MediaWiki API:Tutorial

From binaryoption
Jump to navigation Jump to search
Баннер1
  1. MediaWiki API: Tutorial

The MediaWiki API (Application Programming Interface) is a powerful set of tools that allows developers to interact with a MediaWiki installation programmatically. Instead of relying solely on the web interface, the API enables you to read, write, and modify wiki content, manage users, and perform a wide range of other actions. This tutorial is designed for beginners with little to no prior experience using APIs. We will cover the fundamentals, essential concepts, and provide practical examples to get you started. This article assumes you have a working MediaWiki installation. If not, please refer to the official MediaWiki installation guide.

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 waiter in a restaurant. You (the application) don't go into the kitchen (the MediaWiki server) to get your food (data). Instead, you tell the waiter (the API) what you want, and the waiter brings it back to you. The API defines the "menu" (available actions) and the "language" (request/response formats) used for this communication.

Why use the MediaWiki API?

There are numerous reasons why you might want to use the MediaWiki API:

  • **Automation:** Automate repetitive tasks such as importing data, updating templates, or managing categories.
  • **Integration:** Integrate your wiki with other applications and services. For example, you could create a bot that automatically posts updates from a watchlist to a third-party platform.
  • **Custom Tools:** Develop custom tools and interfaces tailored to your specific needs.
  • **Data Analysis:** Extract data from your wiki for analysis and reporting. You could, for example, analyze revision history to track changes to specific articles.
  • **Bot Development:** Create bots to perform various tasks, like reverting vandalism, adding infoboxes, or performing maintenance tasks. See bots for more information.

Core Concepts

Before diving into examples, let's understand some key concepts:

  • **Actions:** These are the specific tasks you want to perform, such as `query`, `edit`, `upload`, `login`, etc. Each action has its own set of parameters.
  • **Parameters:** These are the pieces of information you send to the API to specify what you want to do. Parameters are usually passed as key-value pairs in the URL or as POST data.
  • **Request Formats:** The most common request format is **GET** for simple read operations and **POST** for more complex operations like editing or uploading.
  • **Response Formats:** The API supports several response formats, but the most common are:
   *   **JSON:** JavaScript Object Notation – a lightweight and human-readable format.
   *   **XML:** Extensible Markup Language – a more verbose and structured format.
   *   **PHP:**  Serialized PHP array (less common).
  • **Authentication:** Some API actions require authentication, meaning you need to prove you have permission to perform them. This is typically done using a username and password or an API token. See API authentication for details.
  • **Rate Limiting:** To prevent abuse, the MediaWiki API has rate limits. This means you can only make a certain number of requests within a given time period. Exceeding the rate limit will result in your requests being blocked. Understanding rate limits is crucial for building reliable applications.

Making your First API Request

Let's start with a simple example: retrieving the title and content of the "Main Page" article. We'll use the `query` action and the `pages` module. We'll also use JSON as the response format.

Here's the URL you would use:

`https://yourwiki.com/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json`

Replace `yourwiki.com` with the actual address of your MediaWiki installation.

Let's break down this URL:

  • `https://yourwiki.com/w/api.php`: The base URL for the MediaWiki API.
  • `action=query`: Specifies that we want to perform a query.
  • `titles=Main%20Page`: Specifies the title of the page we want to retrieve. Note that spaces are encoded as `%20`.
  • `prop=revisions`: Specifies that we want to retrieve the revisions of the page.
  • `rvprop=content`: Specifies that we want to retrieve the content of the revisions.
  • `format=json`: Specifies that we want the response in JSON format.

You can paste this URL into your web browser, and it will display a JSON response containing the content of the Main Page. You can also use a programming language like Python, PHP, or JavaScript to make this request programmatically.

Using a Programming Language (Python Example)

Here's a Python example using the `requests` library:

```python import requests import json

url = "https://yourwiki.com/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json"

response = requests.get(url)

if response.status_code == 200:

   data = json.loads(response.text)
   page = data['query']['pages']
   for page_id, page_data in page.items():
       if page_id != "-1": # Check if the page exists
           content = page_data['revisions'][0]['content']
           print(content)

else:

   print(f"Error: {response.status_code}")

```

This code makes a GET request to the API, checks if the request was successful (status code 200), parses the JSON response, and prints the content of the Main Page. Make sure you have the `requests` library installed (`pip install requests`).

Common API Actions

Here's a brief overview of some common API actions:

  • **`query`:** Retrieves data from the wiki, such as page content, categories, images, and user information. This is the most versatile action.
  • **`edit`:** Edits an existing page or creates a new one.
  • **`upload`:** Uploads a file to the wiki.
  • **`login`:** Logs in a user.
  • **`logout`:** Logs out a user.
  • **`delete`:** Deletes a page or file. (Requires appropriate permissions.)
  • **`categories`:** Retrieves a list of categories.
  • **`search`:** Searches for pages.

Advanced Querying with Modules

The `query` action is incredibly powerful because it allows you to use various modules to retrieve specific types of data. Here are some useful modules:

  • **`pages`:** Retrieves page content, revisions, and other page-related information.
  • **`categories`:** Retrieves information about categories.
  • **`images`:** Retrieves information about images.
  • **`users`:** Retrieves information about users.
  • **`recentchanges`:** Retrieves a list of recent changes.
  • **`links`:** Retrieves a list of links to and from a page. Useful for building a site map.
  • **`extlinks`:** Retrieves external links from a page.

You can combine multiple modules in a single query to retrieve a variety of data. For example:

`https://yourwiki.com/w/api.php?action=query&titles=Main%20Page&prop=categories%7Crevisions&catprop=members&rvprop=content&format=json`

This query retrieves the categories the Main Page belongs to and the content of its current revision.

Editing Pages with the API

To edit a page using the API, you need to use the `edit` action. Here's an example:

`https://yourwiki.com/w/api.php?action=edit&title=Main%20Page&summary=Updated%20by%20API&text=This%20is%20the%20new%20content%20of%20the%20Main%20Page.&token=+\`

  • `action=edit`: Specifies that we want to edit a page.
  • `title=Main%20Page`: Specifies the title of the page to edit.
  • `summary=Updated%20by%20API`: A brief summary of the edit.
  • `text=This%20is%20the%20new%20content%20of%20the%20Main%20Page.`: The new content of the page.
  • `token=+\`: An edit token. **This is crucial.** You need to obtain an edit token to prevent cross-site request forgery (CSRF) attacks. See CSRF protection for more information. You can get an edit token using the `query` action with the `tokens` module.

Here's Python code to edit a page:

```python import requests import json

url = "https://yourwiki.com/w/api.php?action=query&titles=Main%20Page&prop=info&intoken=edit" response = requests.get(url) data = json.loads(response.text) edit_token = data['query']['pages']['1']['edittoken'] # Assuming page ID is 1

edit_url = "https://yourwiki.com/w/api.php?action=edit&title=Main%20Page&summary=Updated%20by%20API&text=This%20is%20the%20new%20content%20of%20the%20Main%20Page.&token=" + edit_token

response = requests.post(edit_url)

if response.status_code == 200:

   print("Page updated successfully!")

else:

   print(f"Error: {response.status_code}")

```

    • Important Considerations:**
  • **Edit Tokens:** Always use an edit token when editing pages.
  • **Error Handling:** Implement proper error handling to catch and handle potential errors.
  • **Rate Limits:** Be mindful of rate limits and implement appropriate delays or throttling mechanisms.
  • **Content Formatting:** Ensure your content is properly formatted for MediaWiki. Use wiki markup or convert your content to wiki markup before sending it to the API.
  • **User Permissions:** Make sure the user you are authenticating with has the necessary permissions to perform the desired actions.

Further Exploration

This tutorial has only scratched the surface of what the MediaWiki API can do. Here are some resources for further exploration:

  • **Official MediaWiki API Documentation:** [1]
  • **API:Tutorial:** [2]
  • **API:Categories:** [3]
  • **API:Search:** [4]
  • **MediaWiki Developer Network:** [5]
  • **Technical Analysis Basics:** [6]
  • **Candlestick Patterns:** [7]
  • **Moving Averages:** [8]
  • **Relative Strength Index (RSI):** [9]
  • **MACD Indicator:** [10]
  • **Bollinger Bands:** [11]
  • **Fibonacci Retracements:** [12]
  • **Support and Resistance Levels:** [13]
  • **Trend Lines:** [14]
  • **Chart Patterns:** [15]
  • **Volume Analysis:** [16]
  • **Elliott Wave Theory:** [17]
  • **Ichimoku Cloud:** [18]
  • **Parabolic SAR:** [19]
  • **Average True Range (ATR):** [20]
  • **Stochastic Oscillator:** [21]
  • **Donchian Channels:** [22]
  • **Heikin Ashi:** [23]
  • **Market Sentiment Analysis:** [24]
  • **Trading Psychology:** [25]
  • **Risk Management in Trading:** [26]
  • **Backtesting Strategies:** [27]

The MediaWiki API offers a vast array of possibilities. With a little practice and experimentation, you can unlock its full potential and create powerful tools to enhance your wiki experience. Remember to consult the official documentation and resources for the most up-to-date information. Also, consider utilizing existing extensions to add functionality to your MediaWiki installation. Finally, always test your code thoroughly in a development environment before deploying it to a production wiki. Understanding the principles of data structures will greatly aid in parsing the API responses.

Help:API

Manual:API

Extension:API

MediaWiki development

Special:ApiSandbox

Configuration

Security

Formatting

Templates

User rights

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

Баннер