mw.Api
Interact with the MediaWiki API.mw.Api is a client library fortheaction API.Anmw.Api object represents the API of a MediaWiki site. For the REST API,seemw.Rest.
var api = new mw.Api();api.get( { action: 'query', meta: 'userinfo'} ).then( ( data ) => { console.log( data );} );Since MW 1.25, multiple values for a parameter can be specified using an array:
var api = new mw.Api();api.get( { action: 'query', meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'} ).then( ( data ) => { console.log( data );} );Since MW 1.26, boolean values for API parameters can be specified natively. Parametervalues set tofalse orundefined will be omitted from the request, as required bythe API.
Classes
- AbortController
- Subset of
AbortControllersufficient for the needs ofmw.Api. - AbortablePromise
A spec-compliant promise with an extra method that allows it to be cancelled, stopping any asyncoperations that will no longer be needed since we won't use their results, like HTTP requests.
Constructor
newmw.Api([options])#
Create an instance ofmw.Api.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
options | mw.Api.Options | optional | See |
- Source:
Methods
abort()#
Abort all unfinished requests issued by this Api object.
- Source:
ajax(parameters, [ajaxOptions]) → {mw.Api~AbortablePromise}#
Perform the API call.
Parameters:
| Name | Type | Attributes | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
parameters | Object | Parameters to the API. See also | |||||||||
ajaxOptions | Object | optional | Parameters to pass to jQuery.ajax. See also Properties:
|
- Source:
Returns:
A promise that settles when the API response is processed.Has an 'abort' method which can be used to abort the request.Seemw.Api~AbortablePromise for an example.
- On success, resolves to
( result, jqXHR )whereresultis the parsed API response. - On an API error, rejects with
( code, result, result, jqXHR )wherecodeis theAPI error code, andresultis as above. When there are multiple errors, the code from the first one will be used.If there is no error code, "unknown" is used. - On other types of errors, rejects with
( 'http', details )wheredetailsis an objectwith three fields:xhr(the jqXHR object),textStatus, andexception.The meaning of the last two fields is as follows:- When the request is aborted (the abort method of the promise is called), textStatusand exception are both set to "abort".
- On a network timeout, textStatus and exception are both set to "timeout".
- On a network error, textStatus is "error" and exception is the empty string.
- When the HTTP response code is anything other than 2xx or 304 (the API does notuse such response codes but some intermediate layer might), textStatus is "error"and exception is the HTTP status text (the text following the status code in thefirst line of the server response). For HTTP/2,
exceptionis always an empty string. - When the response is not valid JSON but the previous error conditions aren't met,textStatus is "parsererror" and exception is the exception object thrown by
JSON.parse.
assertCurrentUser(query) → {Object}#
Extend an API parameter object with an assertion that the user won't change.
This is useful for API calls which create new revisions or log entries. When the currentpage was loaded when the user was logged in, but at the time of the API call the useris not logged in anymore (e.g. due to session expiry), their IP is recorded in the pagehistory or log, which can cause serious privacy issues. Extending the API parameters viathis method ensures that that won't happen, by checking the user's identity that wasembedded into the page when it was rendered against the active session on the server.
When the assertion fails, the API request will fail, with one of the following error codes:
- apierror-assertanonfailed: when the client-side logic thinks the user is anonymousbut the server thinks it is logged in;
- apierror-assertuserfailed: when the client-side logic thinks the user is logged in but theserver thinks it is anonymous;
- apierror-assertnameduserfailed: when both the client-side logic and the server thinks theuser is logged in but they see it logged in under a different username.
Example
api.postWithToken( 'csrf', api.assertCurrentUser( { action: 'edit', ... } ) )Parameters:
| Name | Type | Description |
|---|---|---|
query | Object | Query parameters. The object will not be changed. |
- Since:
- 1.27
- Source:
Returns:
- Type
- Object
badToken(type)#
Indicate that the cached token for a certain action of the API is bad.
Call this if you get a 'badtoken' error when using the token returned bygetToken().You may also want to usepostWithToken() instead, which invalidates bad cached tokensautomatically.
Parameters:
| Name | Type | Description |
|---|---|---|
type | string | Token type |
- Since:
- 1.26
- Source:
chunkedUpload(file, data, [chunkSize], [chunkRetries]) → {jQuery.Promise}#
Upload a file in several chunks.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
file | File | ||
data | Object | Other upload options, see action=upload API docs for more | |
chunkSize | number | optional | Size (in bytes) per chunk (default: 5 MiB) |
chunkRetries | number | optional | Amount of times to retry a failed chunk (default: 1) |
- Source:
Returns:
- Type
- jQuery.Promise
chunkedUploadToStash(file, [data], [chunkSize], [chunkRetries]) → {jQuery.Promise.<function(Object):jQuery.Promise>}#
Upload a file to the stash, in chunks.
This function will return a promise, which when resolved, will pass back a functionto finish the stash upload.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
file | File|HTMLInputElement | ||
data | Object | optional | |
chunkSize | number | optional | Size (in bytes) per chunk (default: 5 MiB) |
chunkRetries | number | optional | Amount of times to retry a failed chunk (default: 1) |
Returns:
Promise that resolves with afunction that should be called to finish the upload.
- Type
- jQuery.Promise.<function(Object):jQuery.Promise>
create(title, params, content) → {jQuery.Promise}#
Create a new page.
Example
new mw.Api().create( 'Sandbox', { summary: 'Load sand particles.' }, 'Sand.');Parameters:
| Name | Type | Description | ||||||
|---|---|---|---|---|---|---|---|---|
title | mw.Title|string | Page title | ||||||
params | Object | Edit API parameters Properties:
| ||||||
content | string |
- Since:
- 1.28
- Source:
Returns:
API response
- Type
- jQuery.Promise
edit(title, transform) → {jQuery.Promise}#
Edit an existing page.
To create a new page, use #create() instead.
Simple transformation:
new mw.Api() .edit( 'Sandbox', function ( revision ) { return revision.content.replace( 'foo', 'bar' ); } ) .then( function () { console.log( 'Saved!' ); } );Set save parameters by returning an object instead of a string:
new mw.Api().edit( 'Sandbox', function ( revision ) { return { text: revision.content.replace( 'foo', 'bar' ), summary: 'Replace "foo" with "bar".', assert: 'bot', minor: true }; }).then( function () { console.log( 'Saved!' );} );Transform asynchronously by returning a promise.
new mw.Api() .edit( 'Sandbox', function ( revision ) { return Spelling .corrections( revision.content ) .then( function ( report ) { return { text: report.output, summary: report.changelog }; } ); } ) .then( function () { console.log( 'Saved!' ); } );Parameters:
| Name | Type | Description |
|---|---|---|
title | mw.Title|string | Page title |
transform | mw.Api.EditTransform | Callback that prepares the edit |
- Since:
- 1.28
- Source:
Returns:
Edit API response
- Type
- jQuery.Promise
get(parameters, [ajaxOptions]) → {mw.Api~AbortablePromise}#
getCategories(title) → {jQuery.Promise.<(Array.<mw.Title>|false)>}#
Get the categories that a particular page on the wiki belongs to.
Parameters:
- Source:
Returns:
Promise that resolves with an array ofcategory titles, or with false if the title was not found.
- Type
- jQuery.Promise.<(Array.<mw.Title>|false)>
getCategoriesByPrefix(prefix) → {jQuery.Promise.<Array.<string>>}#
Get a list of categories that match a certain prefix.
E.g. given "Foo", return "Food", "Foolish people", "Foosball tables"...
Parameters:
| Name | Type | Description |
|---|---|---|
prefix | string | Prefix to match. |
- Source:
Returns:
Promise that resolves with an array of matched categories
- Type
- jQuery.Promise.<Array.<string>>
getEditToken() → {jQuery.Promise}#
getErrorMessage(data) → {jQuery}#
Given an API response indicating an error, get a jQuery object containing a human-readableerror message that you can display somewhere on the page.
For better quality of error messages, it's recommended to use the following options in yourAPI queries:
errorformat: 'html',errorlang: mw.config.get( 'wgUserLanguage' ),errorsuselocal: true,Error messages, particularly for editing pages, may consist of multiple paragraphs of text.Your user interface should have enough space for that.
Example
var api = new mw.Api();// var title = 'Test valid title';var title = 'Test invalid title <>';api.postWithToken( 'watch', { action: 'watch', title: title} ).then( ( data ) => { mw.notify( 'Success!' );}, ( code, data ) => { mw.notify( api.getErrorMessage( data ), { type: 'error' } );} );Parameters:
| Name | Type | Description |
|---|---|---|
data | Object | API response indicating an error |
- Source:
Returns:
Error messages, each wrapped in a<div>
- Type
- jQuery
Given an API response indicating an error, get a jQuery object containing a human-readableerror message that you can display somewhere on the page.
getMessages(messages, [options]) → {jQuery.Promise.<Object.<string,string>>}#
getToken(type, [additionalParams], [ajaxOptions]) → {mw.Api~AbortablePromise.<string>}#
Get a token for a certain action from the API.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
type | string | Token type | |
additionalParams | Object|string | optional | Additional parameters for the API (since 1.35).When given a string, it's treated as the 'assert' parameter (since 1.25). |
ajaxOptions | Object | optional | See |
- Since:
- 1.22
- Source:
Returns:
Received token.
getUserInfo() → {jQuery.Promise.<mw.Api.UserInfo>}#
Get the current user's groups and rights.
- Since:
- 1.27
- Source:
Returns:
isCategory(title) → {jQuery.Promise.<boolean>}#
Determine if a category exists.
Parameters:
- Source:
Returns:
Promise that resolves with a boolean indicatingwhether the category exists.
- Type
- jQuery.Promise.<boolean>
loadMessages(messages, [options]) → {jQuery.Promise}#
Loads a set of messages and add them tomw.messages.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
messages | string|Array.<string> | Messages to retrieve | |
options | Object | optional | Additional parameters for the API call |
- Source:
Returns:
- Type
- jQuery.Promise
mw.messages.loadMessagesIfMissing(messages, [options]) → {jQuery.Promise}#
Loads a set of messages and add them tomw.messages. Only messages that are not already knownare loaded. If all messages are known, the returned promise is resolved immediately.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
messages | string|Array.<string> | Messages to retrieve | |
options | Object | optional | Additional parameters for the API call |
- Since:
- 1.27
- Source:
Returns:
- Type
- jQuery.Promise
mw.messages.login(username, password) → {jQuery.Promise}#
makeAbortablePromise(ajaxOptions) → {Object}#
Helper for adding support for abortable promises in mw.Api methods.
This methods does three things:
- Returns an object with an
abortmethod that can be used as a base foranmw.Api~AbortablePromise. - Updates the provided
ajaxOptionswith asignalthat will be triggered by said method. - If the
ajaxOptionsalready had asignal, forwards evens from it to the new one.
This ensures that both the signal provided inajaxOptions (if any) and theabort method on the returned object can cancel the HTTP requests.It's only needed when supporting the old-stylepromise.abort() method.
Examples
API method only supporting AbortController
mw.Api.prototype.getWhatever = function ( params, ajaxOptions ) { return this.get( Object.assign( { foo: 'bar' }, params ), ajaxOptions ) .then( ... );}API method supporting promise.abort() method too
mw.Api.prototype.getWhatever = function ( params, ajaxOptions ) { ajaxOptions = ajaxOptions || {}; const abortable = this.makeAbortablePromise( ajaxOptions ); return this.get( Object.assign( { foo: 'bar' }, params ), ajaxOptions ) .then( ... ) .promise( abortable );}Parameters:
| Name | Type | Description |
|---|---|---|
ajaxOptions | Object | Options object to modify (will set |
- Since:
- 1.44
- Source:
Returns:
Base object formw.Api~AbortablePromise
- Type
- Object
newSection(title, header, message, [additionalParams]) → {jQuery.Promise}#
parse(content, additionalParams) → {jQuery.Promise.<string>}#
Convenience method for 'action=parse'.
Parameters:
| Name | Type | Description |
|---|---|---|
content | string|mw.Title | Content to parse, either as a wikitext string ora mw.Title. |
additionalParams | Object | Parameters object to set custom settings, e.g. |
- Source:
Returns:
Promise that resolves with the parsed HTML ofwikitext
- Type
- jQuery.Promise.<string>
post(parameters, [ajaxOptions]) → {mw.Api~AbortablePromise}#
postWithEditToken(params, [ajaxOptions]) → {jQuery.Promise}#
csrf token.postWithToken(tokenType, params, [ajaxOptions]) → {mw.Api~AbortablePromise}#
Post to API with the specified type of token. If we have no token, get one and try to post.If we already have a cached token, try using that, and if the request fails using the cached token,blank it out and start over.
Example
For example, to change a user option, you could do:
new mw.Api().postWithToken( 'csrf', { action: 'options', optionname: 'gender', optionvalue: 'female'} );Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
tokenType | string | The name of the token, like options or edit. | |
params | Object | API parameters | |
ajaxOptions | Object | optional |
- Since:
- 1.22
- Source:
Returns:
Seepost()
prepareExtensibleApiRequest(hookName) → {jQuery.Promise.<Object>}#
Prepare an extensible API request.
This is a utility method to allow mw.hook implementations to add data to params sentwith an API request.
For example usage, see mediawiki.ready/index.js#logoutViaPost:api.prepareExtensibleApiRequest( 'extendLogout' ).then( ( params ) => { ... } )
Implementations ofhookName should do something like the following, wherehookNameisextendLogout in this example:
mw.hook( 'extendLogout' ).add( ( data ) => {data.promise = data.promise.then( () => {// Return a promisereturn collectClientHintsData().then( ( userAgentHighEntropyValues ) => {// Set the data.params.{yourUniqueKey} that will be included in the API// requestdata.params.customData = { clientHints: userAgentHighEntropyValues };} );} );} );
Parameters:
| Name | Type | Description |
|---|---|---|
hookName | string | Name of the hook to use with mw.hook().fire() |
- Source:
Returns:
Updated parameter data from implementationsofhookName to include with the API request.
- Type
- jQuery.Promise.<Object>
rollback(page, user, [params]) → {jQuery.Promise}#
Convenience method foraction=rollback.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
page | string|mw.Title | ||
user | string | ||
params | Object | optional | Additional parameters |
- Since:
- 1.28
- Source:
Returns:
- Type
- jQuery.Promise
action=rollback.saveOption(name, value, [params]) → {jQuery.Promise}#
Asynchronously save the value of a single user option using the API.SeesaveOptions().
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name | string | ||
value | string|null | ||
params | Object | optional | additional parameters for API. |
- Source:
Returns:
- Type
- jQuery.Promise
saveOptions(options, [params]) → {jQuery.Promise}#
Asynchronously save the values of user options using theOptions API.
If a value ofnull is provided, the given option will be reset to the default value.
Any warnings returned by the API, including warnings about invalid option names or values,are ignored. However, do not rely on this behavior.
If necessary, the options will be saved using several sequential API requests. Only one promiseis always returned that will be resolved when all requests complete.
If a request from a previoussaveOptions() call is still pending, this will wait for it to becompleted, otherwise MediaWiki gets sad. No requests are sent for anonymous users, as theywould fail anyway. SeeT214963.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
options | Object | Options as a | |
params | Object | optional | additional parameters for API. |
- Source:
Returns:
- Type
- jQuery.Promise
Asynchronously save the values of user options using theOptions API.
unwatch(pages) → {jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>}#
Convenience method foraction=watch&unwatch=1.
Parameters:
| Name | Type | Description |
|---|---|---|
pages | string|mw.Title|Array.<string>|Array.<mw.Title> | Full page name or instance of mw.Title, or anarray thereof. If an array is passed, the return value passed to the promise will also be anarray of appropriate objects. |
- Source:
Returns:
A promise that resolveswith an object (or array of objects) describing each page that was passed in and itscurrent watched/unwatched status.
action=watch&unwatch=1.upload(file, data) → {jQuery.Promise}#
Upload a file to MediaWiki.
The file will be uploaded using AJAX and FormData.
Parameters:
| Name | Type | Description |
|---|---|---|
file | HTMLInputElement|File|Blob | HTML input type=file element with a file already insideof it, or a File object. |
data | Object | Other upload options, see action=upload API docs for more |
- Source:
Returns:
- Type
- jQuery.Promise
uploadFromStash(filekey, data) → {jQuery.Promise}#
uploadToStash(file, [data]) → {jQuery.Promise.<function(Object):jQuery.Promise>}#
Upload a file to the stash.
This function will return a promise, which when resolved, will pass back a functionto finish the stash upload. You can call that function with an argument containingmore, or conflicting, data to pass to the server.
Example
// upload a file to the stash with a placeholder filenameapi.uploadToStash( file, { filename: 'testing.png' } ).done( function ( finish ) { // finish is now the function we can use to finalize the upload // pass it a new filename from user input to override the initial value finish( { filename: getFilenameFromUser() } ).done( function ( data ) { // the upload is complete, data holds the API response } );} );Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
file | File|HTMLInputElement | ||
data | Object | optional |
- Source:
Returns:
Promise that resolves with afunction that should be called to finish the upload.
- Type
- jQuery.Promise.<function(Object):jQuery.Promise>
watch(pages, [expiry]) → {jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>}#
Convenience method foraction=watch.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
pages | string|mw.Title|Array.<string>|Array.<mw.Title> | Full page name or instance of mw.Title, or anarray thereof. If an array is passed, the return value passed to the promise will also be anarray of appropriate objects. | |
expiry | string | optional | When the page should expire from the watchlist. If omitted, thepage will not expire. |
- Since:
- 1.35 - expiry parameter can be passed when Watchlist Expiry is enabled
- Source:
Returns:
A promise that resolveswith an object (or array of objects) describing each page that was passed in and itscurrent watched/unwatched status.
action=watch.Type Definitions
Options#
Type:
Properties:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
parameters | Object | optional | { action: 'query', format: 'json' } | Default queryparameters for API requests |
ajax | Object | optional | { url: mw.util.wikiScript( 'api' ), timeout: 30 * 1000, dataType: 'json' } | Default options for jQuery#ajax |
useUS | boolean | optional | Whether to use U+001F when joining multi-valuedparameters (since 1.28). Default is true if ajax.url is not set, false otherwise forcompatibility. | |
userAgent | string | optional | User agent string to use for API requests (since 1.44).This should identify what component (extension, gadget, user script) is making the request. |
- Source: