Expand all

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 ofAbortController sufficient 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:

NameTypeAttributesDescription
optionsmw.Api.Options optional

Seemw.Api.Options. This can also be overridden foreach request by passing them toget() orpost() (or directly toajax()) later on.

Source:

Methods

abort()#

Abort all unfinished requests issued by this Api object.

Source:
Abort all unfinished requests issued by this Api object.

ajax(parameters, [ajaxOptions]) → {mw.Api~AbortablePromise}#

Perform the API call.

Parameters:

NameTypeAttributesDescription
parametersObject

Parameters to the API. See alsomw.Api.Options

ajaxOptionsObject optional

Parameters to pass to jQuery.ajax. See alsomw.Api.Options

Properties:
NameTypeAttributesDescription
signalAbortSignal optional

Signal which can be used to abort the request.Seemw.Api~AbortController for an example. (since 1.44)

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 ) whereresult is the parsed API response.
  • On an API error, rejects with( code, result, result, jqXHR ) wherecode is 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 ) wheredetails is 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,exception is 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 byJSON.parse.
Type
mw.Api~AbortablePromise
Perform the API call.

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:

NameTypeDescription
queryObject

Query parameters. The object will not be changed.

Since:
  • 1.27
Source:

Returns:

Type
Object
Extend an API parameter object with an assertion that the user won't change.

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:

NameTypeDescription
typestring

Token type

Since:
  • 1.26
Source:
Indicate that the cached token for a certain action of the API is bad.

chunkedUpload(file, data, [chunkSize], [chunkRetries]) → {jQuery.Promise}#

Upload a file in several chunks.

Parameters:

NameTypeAttributesDescription
fileFile
dataObject

Other upload options, see action=upload API docs for more

chunkSizenumber optional

Size (in bytes) per chunk (default: 5 MiB)

chunkRetriesnumber optional

Amount of times to retry a failed chunk (default: 1)

Source:

Returns:

Type
jQuery.Promise
Upload a file in several chunks.

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:

NameTypeAttributesDescription
fileFile|HTMLInputElement
dataObject optional
chunkSizenumber optional

Size (in bytes) per chunk (default: 5 MiB)

chunkRetriesnumber optional

Amount of times to retry a failed chunk (default: 1)

Source:
See:

Returns:

Promise that resolves with afunction that should be called to finish the upload.

Type
jQuery.Promise.<function(Object):jQuery.Promise>
Upload a file to the stash, in chunks.

create(title, params, content) → {jQuery.Promise}#

Create a new page.

Example

new mw.Api().create( 'Sandbox',    { summary: 'Load sand particles.' },    'Sand.');

Parameters:

NameTypeDescription
titlemw.Title|string

Page title

paramsObject

Edit API parameters

Properties:
NameTypeDescription
summarystring

Edit summary

contentstring
Since:
  • 1.28
Source:

Returns:

API response

Type
jQuery.Promise
Create a new page.

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:

NameTypeDescription
titlemw.Title|string

Page title

transformmw.Api.EditTransform

Callback that prepares the edit

Since:
  • 1.28
Source:

Returns:

Edit API response

Type
jQuery.Promise
Edit an existing page.

get(parameters, [ajaxOptions]) → {mw.Api~AbortablePromise}#

Perform API get request. Seeajax() for details.

Parameters:

NameTypeAttributesDescription
parametersObject
ajaxOptionsObject optional
Source:

Returns:

Type
mw.Api~AbortablePromise
Perform API get request.

getCategories(title) → {jQuery.Promise.<(Array.<mw.Title>|false)>}#

Get the categories that a particular page on the wiki belongs to.

Parameters:

NameTypeDescription
titlemw.Title|string
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)>
Get the categories that a particular page on the wiki belongs to.

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:

NameTypeDescription
prefixstring

Prefix to match.

Source:

Returns:

Promise that resolves with an array of matched categories

Type
jQuery.Promise.<Array.<string>>
Get a list of categories that match a certain prefix.

getEditToken() → {jQuery.Promise}#

API helper to grab a csrf token.

Source:

Returns:

Received token.

Type
jQuery.Promise
API helper to grab a csrf token.

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:

NameTypeDescription
dataObject

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>>}#

Get a set of messages.

Parameters:

NameTypeAttributesDescription
messagesstring|Array.<string>

Messages to retrieve

optionsObject optional

Additional parameters for the API call

Since:
  • 1.27
Source:

Returns:

Type
jQuery.Promise.<Object.<string,string>>
Get a set of messages.

getToken(type, [additionalParams], [ajaxOptions]) → {mw.Api~AbortablePromise.<string>}#

Get a token for a certain action from the API.

Parameters:

NameTypeAttributesDescription
typestring

Token type

additionalParamsObject|string optional

Additional parameters for the API (since 1.35).When given a string, it's treated as the 'assert' parameter (since 1.25).

ajaxOptionsObject optional

Seemw.Api#ajax (since 1.44)

Since:
  • 1.22
Source:

Returns:

Received token.

Type
mw.Api~AbortablePromise.<string>
Get a token for a certain action from the API.

getUserInfo() → {jQuery.Promise.<mw.Api.UserInfo>}#

Get the current user's groups and rights.

Since:
  • 1.27
Source:

Returns:

Type
jQuery.Promise.<mw.Api.UserInfo>
Get the current user's groups and rights.

isCategory(title) → {jQuery.Promise.<boolean>}#

Determine if a category exists.

Parameters:

NameTypeDescription
titlemw.Title|string
Source:

Returns:

Promise that resolves with a boolean indicatingwhether the category exists.

Type
jQuery.Promise.<boolean>
Determine if a category exists.

loadMessages(messages, [options]) → {jQuery.Promise}#

Loads a set of messages and add them tomw.messages.

Parameters:

NameTypeAttributesDescription
messagesstring|Array.<string>

Messages to retrieve

optionsObject optional

Additional parameters for the API call

Source:

Returns:

Type
jQuery.Promise
Loads a set of messages and add them tomw.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:

NameTypeAttributesDescription
messagesstring|Array.<string>

Messages to retrieve

optionsObject optional

Additional parameters for the API call

Since:
  • 1.27
Source:

Returns:

Type
jQuery.Promise
Loads a set of messages and add them tomw.messages.

login(username, password) → {jQuery.Promise}#

Parameters:

NameTypeDescription
usernamestring
passwordstring
Source:

Returns:

Type
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 anabort method that can be used as a base foranmw.Api~AbortablePromise.
  • Updates the providedajaxOptions with asignal that will be triggered by said method.
  • If theajaxOptions already 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:

NameTypeDescription
ajaxOptionsObject

Options object to modify (will setajaxOptions.signal)

Since:
  • 1.44
Source:

Returns:

Type
Object
Helper for adding support for abortable promises in mw.Api methods.

newSection(title, header, message, [additionalParams]) → {jQuery.Promise}#

Post a new section to the page.

Parameters:

NameTypeAttributesDescription
titlemw.Title|string

Target page

headerstring
messagestring

wikitext message

additionalParamsObject optional

Additional API parameters, e.g.{ redirect: true }

Source:
See:

Returns:

Type
jQuery.Promise
Post a new section to the page.

parse(content, additionalParams) → {jQuery.Promise.<string>}#

Convenience method for 'action=parse'.

Parameters:

NameTypeDescription
contentstring|mw.Title

Content to parse, either as a wikitext string ora mw.Title.

additionalParamsObject

Parameters object to set custom settings, e.g.redirects,sectionpreview.prop should not be overridden.

Source:

Returns:

Promise that resolves with the parsed HTML ofwikitext

Type
jQuery.Promise.<string>
Convenience method for 'action=parse'.

post(parameters, [ajaxOptions]) → {mw.Api~AbortablePromise}#

Perform API post request. Seeajax() for details.

Parameters:

NameTypeAttributesDescription
parametersObject
ajaxOptionsObject optional
Source:

Returns:

Type
mw.Api~AbortablePromise
Perform API post request.

postWithEditToken(params, [ajaxOptions]) → {jQuery.Promise}#

Post to API withcsrf token. See#postWithToken

Parameters:

NameTypeAttributesDescription
paramsObject

API parameters

ajaxOptionsObject optional
Source:

Returns:

Type
jQuery.Promise
Post to API withcsrf 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:

NameTypeAttributesDescription
tokenTypestring

The name of the token, like options or edit.

paramsObject

API parameters

ajaxOptionsObject optional
Since:
  • 1.22
Source:

Returns:

Type
mw.Api~AbortablePromise
Post to API with the specified type of token.

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:

NameTypeDescription
hookNamestring

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>
Prepare an extensible API request.

rollback(page, user, [params]) → {jQuery.Promise}#

Convenience method foraction=rollback.

Parameters:

NameTypeAttributesDescription
pagestring|mw.Title
userstring
paramsObject optional

Additional parameters

Since:
  • 1.28
Source:

Returns:

Type
jQuery.Promise
Convenience method foraction=rollback.

saveOption(name, value, [params]) → {jQuery.Promise}#

Asynchronously save the value of a single user option using the API.SeesaveOptions().

Parameters:

NameTypeAttributesDescription
namestring
valuestring|null
paramsObject optional

additional parameters for API.

Source:

Returns:

Type
jQuery.Promise
Asynchronously save the value of a single user option using the API.

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:

NameTypeAttributesDescription
optionsObject

Options as a{ name: value, … } object

paramsObject 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:

NameTypeDescription
pagesstring|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.

Type
jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>
Convenience method foraction=watch&unwatch=1.

upload(file, data) → {jQuery.Promise}#

Upload a file to MediaWiki.

The file will be uploaded using AJAX and FormData.

Parameters:

NameTypeDescription
fileHTMLInputElement|File|Blob

HTML input type=file element with a file already insideof it, or a File object.

dataObject

Other upload options, see action=upload API docs for more

Source:

Returns:

Type
jQuery.Promise
Upload a file to MediaWiki.

uploadFromStash(filekey, data) → {jQuery.Promise}#

Finish an upload in the stash.

Parameters:

NameTypeDescription
filekeystring
dataObject
Source:

Returns:

Type
jQuery.Promise
Finish an upload in the stash.

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:

NameTypeAttributesDescription
fileFile|HTMLInputElement
dataObject optional
Source:

Returns:

Promise that resolves with afunction that should be called to finish the upload.

Type
jQuery.Promise.<function(Object):jQuery.Promise>
Upload a file to the stash.

watch(pages, [expiry]) → {jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>}#

Convenience method foraction=watch.

Parameters:

NameTypeAttributesDescription
pagesstring|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.

expirystring 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.

Type
jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>
Convenience method foraction=watch.

Type Definitions

EditTransform(revision) → {string|Object|jQuery.Promise}#

Parameters:

NameTypeDescription
revisionObject

Current revision

Properties:
NameTypeDescription
contentstring

Current revision content

Source:

Returns:

New content, object with editAPI parameters, or promise providing one of those.

Type
string|Object|jQuery.Promise

Options#

Type:

Properties:

NameTypeAttributesDefaultDescription
parametersObject optional
{ action: 'query', format: 'json' }

Default queryparameters for API requests

ajaxObject optional
{ url: mw.util.wikiScript( 'api' ), timeout: 30 * 1000, dataType: 'json' }

Default options for jQuery#ajax

useUSboolean 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.

userAgentstring 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:

UserInfo#

Type:

Properties:

NameTypeDescription
groupsArray.<string>

User groups that the current user belongs to

rightsArray.<string>

Current user's rights

Source:

WatchedPage#

Type:

Properties:

NameTypeDescription
titlestring

Full page name

watchedboolean

Whether the page is now watched (true) or unwatched (false)

Source: