API:Extensions

From MediaWiki.org
Jump to: navigation, search
Tools clipart.png This page is part of the MediaWiki API documentation.
Language: English  • Deutsch
MediaWiki API

Quick overview:

v · d · e
Gnome-preferences-other.svg Extensions: Tag Extensions Parser Functions Hooks Special Pages Skins Magic Words API

Contents

[edit] Creating API modules in extensions

Extensions can also add API modules. Create a new class that inherits ApiBase (for a top-level module), ApiQueryBase (for a non-generator submodule of action=query) or ApiQueryGeneratorBase (for a submodule of action=query with generator functionality) and implement the methods execute(), getAllowedParams(), getParamDescription(), getDescription() and getVersion().

A generator module is somewhat like UNIX piping, where the output of one module is the input of another. For example: You can ask for a list of all pages with list=allpages, and you can enumerate images on specific pages (by specifying page titles) with prop=images. allpages can also act as a generator, so you can "pipe" it to prop=images. By convention when a module acts as a generator its parameters, often the same as in its regular mode, are prefixed with 'g'. Thus api.php?action=query&generator=allpages&gaplimit=8&prop=images&imlimit=15 generates a list of the first 8 wiki pages, and from them shows up to 12 images in total. Generator modules also need to implement executeGenerator().

When you've created your new class, you need to register it with the API by adding it to $wgAPIModules (top-level modules, selected using action=), $wgAPIPropModules (prop= modules), $wgAPIMetaModules (meta= modules) or $wgAPIListModules (list= modules), like this:

 // Register the ApiMyExt class as handler for action=myext
$wgAPIModules['myext'] = 'ApiMyExt';

It's possible to override core modules.

[edit] Extending core modules

Since MediaWiki 1.14, it's possible to extend core modules' functionality using the following hooks:

[edit] List of extensions with API functionality

See API extensions for examples of extensions that add or extend to the API.

[edit] Caching

By default ApiMain leaves caching of API calls up to the callee ('Cache-Control: private')! To modify this behavior for high volume requests add the following somewhere in your execute() method:

// Tell squids to cache
$this->getMain()->setCacheMode( 'public' );
// Set the squid & private cache time in seconds
$this->getMain()->setCacheMaxAge( 300 );

[edit] Sample API extension

This is an example API extension that receives face (i.e. an emoticon) as a parameter and outputs various data (viz. reply emoticons and predictions) in response. For example:

to generate:

<api>
  <apisampleoutput apiresponses="are as follows">
    <nonverbalresponse emoticon="o_O"/>
    <predictions yourweek="You will learn something interesting and useful about API extensions this week"
      yourlife="You will become a successful MediaWiki hacker, which will serve you well in your life"
      eternity="Eventually all life will be destroyed in the heat death"/>
  </apisampleoutput>
</api>

To install it requires the usual procedure, i.e. copying the following three files into $IP/extensions/SampleApiExtension and adding to the end of LocalSettings.php:

require_once("$IP/extensions/SampleApiExtension/SampleApiExtension.php");

[edit] SampleApiExtension.php

<?php
 
// Take credit for your work.
$wgExtensionCredits['api'][] = array(
 
   // The full path and filename of the file. This allows MediaWiki
   // to display the Subversion revision number on Special:Version.
   'path' => __FILE__,
 
   // The name of the extension, which will appear on Special:Version.
   'name' => 'Sample API Function',
 
   // A description of the extension, which will appear on Special:Version.
   'description' => 'A simple sample API extension',
 
   // Alternatively, you can specify a message key for the description.
   'descriptionmsg' => 'sampleapiextension-desc',
 
   // The version of the extension, which will appear on Special:Version.
   // This can be a number or a string.
   'version' => 1, 
 
   // Your name, which will appear on Special:Version.
   'author' => 'Me',
 
   // The URL to a wiki page/web page with information about the extension,
   // which will appear on Special:Version.
   'url' => 'https://www.mediawiki.org/wiki/API:Extensions',
 
);
 
// Map class name to filename for autoloading
$wgAutoloadClasses['ApiSample'] = dirname( __FILE__ )
        . '/ApiSampleApiExtension.php';
 
// Map module name to class name
   $wgAPIModules['apisampleoutput'] = 'ApiSample';
 
// Load the internationalization file
$wgExtensionMessagesFiles['myextension'] = dirname( __FILE__ ) 
        . '/SampleApiExtension.i18n.php';
 
// Return true so that MediaWiki continues to load extensions.
return true;

[edit] ApiSampleApiExtension.php

<?
class ApiSample extends ApiBase {
        public function execute() {
                global $wgUser, $wgOut;
 
                // Get the parameters
                $params = $this->extractRequestParams();
 
                // Default response is a wink ;)
                $emoticon = ';)';
                $result = $this->getResult();
                // Other responses depend on the value of the face parameter
                switch ( $params['face'] ) {
                        case 'O_o':
                                $emoticon = 'o_O';
                                break;
                        case 'o_O':
                                $emoticon = 'O_o';
                                break;
                }
                // Top level
                $this->getResult()->addValue( null, $this->getModuleName(), array ( 'apiresponses' => 'are as follows' ) );
                // Deliver a facial expression in reply
                $this->getResult()->addValue( null, $this->getModuleName()
                        , array ( 'nonverbalresponse' => array ( 'emoticon' => $emoticon ) ) );
                // Offer a few predictions about the user's future
                $this->getResult()->addValue( null, $this->getModuleName()
                        , array ( 'predictions' => array (
                                'yourweek' => 'You will learn something interesting and useful about API extensions '
                                        .'this week' ,
                                'yourlife' => 'You will become a successful MediaWiki hacker, which will serve you well '
                                        .'in your life' ,
                                'eternity' => 'Eventually all life will be destroyed in the heat death' ) ) );
                return true;
        }
 
        // Version
        public function getVersion() {
                return __CLASS__ . ': $Id$';
        }
 
        // Description
        public function getDescription() {
                return 'Get both nonverbal and verbal responses to your input.';
        }
 
        // Face parameter.
        public function getAllowedParams() {
                return array(
                        'face' => array (
                                ApiBase::PARAM_TYPE => 'string',
                                ApiBase::PARAM_REQUIRED => true
                        ),
                );
        }
 
        // Describe the parameter
        public function getParamDescription() {
                return array( 'face' => 'The face you want to make to the API (e.g. o_O)' );
        }
 
        // Get examples
         public function getExamples() {
        return array(
                'Get a sideways look (and the usual predictions)',
                ' api.php?action=apisampleoutput&face=O_o&format=xml' );
        }
}

[edit] SampleApiExtension.i18n.php

<?php
$messages = array();
$messages['en'] = array(
        'sampleapiextension-desc' => "This extension implements an apisampleoutput API module to provide, in response to "
        ."input the user provides in the 'face' field, an emoticon and some plausible predictions. For example, try "
        ."api.php?action=apisampleoutput&face=O_o&format=xml . For more information, see api.php",
);
Personal tools
Namespaces

Variants
Actions
Navigation
Support
Download
Development
Communication
Print/export
Toolbox