API:Extensions
![]() |
This page is part of the MediaWiki API documentation. |
Language: | English • Deutsch |
---|
Quick overview:
- Quick start guide
- FAQ
- Tutorial
- Formats
- Error reporting
- Restricting usage
- Authentication
- Queries
- Search suggestions
- Expanding templates and rendering
- Purging pages' caches
- Parameter information
- Changing wiki content
- Watchlist feed
- Extensions
- Using the API in MediaWiki and extensions
- Miscellaneous
- Implementation
- Client code
![]() |
Tag Extensions | Parser Functions | Hooks | Special Pages | Skins | Magic Words | API |
Contents |
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.
Extending core modules
Since MediaWiki 1.14, it's possible to extend core modules' functionality using the following hooks:
- APIGetAllowedParams to add or modify the module's parameter list
- APIGetParamDescription to add or modify the module's parameter descriptions
- APIAfterExecute to do something after the module has been executed (but before the result has been output)
- Use APIQueryAfterExecute for
prop=
,list=
andmeta=
modules- If the module is run in generator mode, APIQueryGeneratorAfterExecute will be called instead
- Use APIQueryAfterExecute for
List of extensions with API functionality
See API extensions for examples of extensions that add or extend to the API.
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 );
Returning errors
Some errors will be automatically generated if certain conditions that you set up are not met; for example, if the user fails to provide a title, then the "missingparam" error will be thrown if you have set getAllowedParams as follows:
// Title parameter. public function getAllowedParams() { return array( 'title' => array ( ApiBase::PARAM_TYPE => 'string', ApiBase::PARAM_REQUIRED => true ), ); }
Sometimes the types of error conditions set up by the methods supplied by ApiBase will not suffice and you will have to set up your own conditions. E.g., if you wanted to prevent the client from using interwiki links (e.g. wikiquote:MediaWiki) as titles, you might use:
$pageObj = $this->getTitleOrPageId( $params ); $titleObj = $pageObj->getTitle(); if ( $titleObj->isExternal() ) { $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) ); }
That would throw the error defined in messageMap. See documentation for ApiBase::dieUsage, ApiBase::dieUsageMsg, and ApiBase::getPossibleErrors. For an example of how the latter is done, see ApiEditPage::getPossibleErrors.
Returning results
See the example at Manual:ApiResult.php#Example.
Sample API extension
See also API:Implementation_Strategy#Boilerplates.
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");
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;
ApiSampleApiExtension.php
<? class ApiSample extends ApiBase { public function execute() { // 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; } // Description public function getDescription() { return 'Get both nonverbal and verbal responses to your input.'; } // Face parameter. public function getAllowedParams() { return array_merge( parent::getAllowedParams(), array( 'face' => array ( ApiBase::PARAM_TYPE => 'string', ApiBase::PARAM_REQUIRED => true ), ) ); } // Describe the parameter public function getParamDescription() { return array_merge( parent::getParamDescription(), array( 'face' => 'The face you want to make to the API (e.g. o_O)' ) ); } // Get examples public function getExamples() { return array( 'api.php?action=apisampleoutput&face=O_o&format=xml' => 'Get a sideways look (and the usual predictions)' ); } }
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", );