API:Calling internally
![]() |
This page is part of the MediaWiki API documentation. |
Language: | English • 日本語 |
---|
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
Sometimes other parts of the code may wish to use the data access and aggregation functionality of the API.
If your code is just going to edit some content, please consider using WikiPage::doEdit()
instead of an API.
Here are the steps needed to accomplish such usage:
1) If you are executing in the context of existing request from the user ($wgRequest is available), prepare request parameters using DerivativeRequest class. All parameters are the same as if making the request over the web.
global $wgRequest; $params = new DerivativeRequest( $wgRequest, array( 'action' => 'query', 'list' => 'allpages', 'apnamespace' => 0, 'aplimit' => 10, 'apprefix' => $search) );
2) Create and execute ApiMain instance. Because the parameter is an instance of a DerivativeRequest object, ApiMain will not execute any formatting printers, nor will it handle any errors. A parameter error or any other internal error will cause an exception that may be caught in the calling code.
$api = new ApiMain( $params ); $api->execute();
Important: If you want to create or edit pages, you have to send another parameter = true, when creating the ApiMain object. Like so:
$api = new ApiMain( $params, true ); // default is false $api->execute();
You may also need to send an edit token along as the last parameter when making edits or changes. You can get the edit token like so:
global $wgUser; $token = $wgUser->editToken();
3) Get the resulting data array.
$data = & $api->getResultData();
Here is a complete example taken from Extension:WikiLove (as of r112758):
$api = new ApiMain( new DerivativeRequest( $wgRequest, array( 'action' => 'edit', 'title' => $talk->getFullText(), 'appendtext' => ( $talk->exists() ? "\n\n" : '' ) . wfMsgForContent( 'newsectionheaderdefaultlevel', $params['subject'] ) . "\n\n" . $params['text'], 'token' => $params['token'], 'summary' => wfMsgForContent( 'wikilove-summary', $wgParser->stripSectionName( $params['subject'] ) ), 'notminor' => true ), false // was posted? ), true // enable write? ); $api->execute();
Note: A description of this process for use outside of extensions is available.
If there is no user request context, you can use FauxRequest
instead of DerivativeRequest
. Using FauxRequest
for write operations without passing $wgRequest
context causes bug 34838.
UsageException
. If its possible for your code to send an invalid parameter, you should probably call the api from inside a try/catch block