mw.Api(optionsopt)

Interact with the API of a particular MediaWiki site. mw.Api objects represent the API of one particular MediaWiki site.

var api = new mw.Api();
api.get( {
    action: 'query',
    meta: 'userinfo'
} ).done( function ( 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'
} ).done( function ( data ) {
    console.log( data );
} );

Since MW 1.26, boolean values for API parameters can be specified natively. Parameter values set to false or undefined will be omitted from the request, as required by the API.

Constructor

new mw.Api(optionsopt) #

Client library for the action API. See mw.Rest for the REST API. See also https://www.mediawiki.org/wiki/API:Main_page.

Parameters:

Name Type Attributes Description
options mw.Api.Options <optional>

See mw.Api.Options. This can also be overridden for each request by passing them to get() or post() (or directly to ajax()) later on.

Source:
Client library for the action API.

Methods

abort() #

Abort all unfinished requests issued by this Api object.

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

ajax(parameters, ajaxOptionsopt) → {jQuery.Promise} #

Perform the API call.

Parameters:

Name Type Attributes Description
parameters Object

Parameters to the API. See also mw.Api.Options

ajaxOptions Object <optional>

Parameters to pass to jQuery.ajax. See also mw.Api.Options

Source:

Returns:

A promise that settles when the API response is processed. Has an 'abort' method which can be used to abort the request.

  • On success, resolves to ( result, jqXHR ) where result is the parsed API response.
  • On an API error, rejects with ( code, result, result, jqXHR ) where code is the API error code, and result is 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 ) where details is an object with three fields: xhr (the jqXHR object), textStatus, and exception. The meaning of the last two fields is as follows:
    • When the request is aborted (the abort method of the promise is called), textStatus and 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 not use 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 the first 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 by JSON.parse.
Type
jQuery.Promise
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 current page was loaded when the user was logged in, but at the time of the API call the user is not logged in anymore (e.g. due to session expiry), their IP is recorded in the page history or log, which can cause serious privacy issues. Extending the API parameters via this method ensures that that won't happen, by checking the user's identity that was embedded 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 anonymous but the server thinks it is logged in;
  • apierror-assertuserfailed: when the client-side logic thinks the user is logged in but the server thinks it is anonymous;
  • apierror-assertnameduserfailed: when both the client-side logic and the server thinks the user 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
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 by getToken(). You may also want to use postWithToken() instead, which invalidates bad cached tokens automatically.

Parameters:

Name Type Description
type string

Token type

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

chunkedUpload(file, data, chunkSizeopt, chunkRetriesopt) → {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
Upload a file in several chunks.

chunkedUploadToStash(file, dataopt, chunkSizeopt, chunkRetriesopt) → {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 function to 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)

Source:
See:

Returns:

Promise that resolves with a function 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:

Name Type Description
title mw.Title | string

Page title

params Object

Edit API parameters

Properties
Name Type Description
summary string

Edit summary

content string
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:

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
Edit an existing page.

get(parameters, ajaxOptionsopt) → {jQuery.Promise} #

Perform API get request. See ajax() for details.

Parameters:

Name Type Attributes Description
parameters Object
ajaxOptions Object <optional>
Source:

Returns:

Type
jQuery.Promise
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:

Name Type Description
title mw.Title | string
Source:

Returns:

Promise that resolves with an array of category 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:

Name Type Description
prefix string

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-readable error message that you can display somewhere on the page.

For better quality of error messages, it's recommended to use the following options in your API 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( function ( data ) {
  mw.notify( 'Success!' );
}, function ( 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-readable error message that you can display somewhere on the page.

getMessages(messages, optionsopt) → {jQuery.Promise.<Object.<string, string>>} #

Get a set of messages.

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.<Object.<string, string>>
Get a set of messages.

getToken(type, additionalParamsopt) → {jQuery.Promise.<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).

Since:
  • 1.22
Source:

Returns:

Received token.

Type
jQuery.Promise.<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:

Name Type Description
title mw.Title | string
Source:

Returns:

Promise that resolves with a boolean indicating whether the category exists.

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

loadMessages(messages, optionsopt) → {jQuery.Promise} #

Loads a set of messages and add them to mw.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
Loads a set of messages and add them to mw.messages.

loadMessagesIfMissing(messages, optionsopt) → {jQuery.Promise} #

Loads a set of messages and add them to mw.messages. Only messages that are not already known are 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
Loads a set of messages and add them to mw.messages.

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

Parameters:

Name Type Description
username string
password string
Source:

Returns:

See post()

Type
jQuery.Promise

newSection(title, header, message, additionalParamsopt) → {jQuery.Promise} #

Post a new section to the page.

Parameters:

Name Type Attributes Description
title mw.Title | string

Target page

header string
message string

wikitext message

additionalParams Object <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:

Name Type Description
content string | mw.Title

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

additionalParams Object

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

Source:

Returns:

Promise that resolves with the parsed HTML of wikitext

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

post(parameters, ajaxOptionsopt) → {jQuery.Promise} #

Perform API post request. See ajax() for details.

Parameters:

Name Type Attributes Description
parameters Object
ajaxOptions Object <optional>
Source:

Returns:

Type
jQuery.Promise
Perform API post request.

postWithEditToken(params, ajaxOptionsopt) → {jQuery.Promise} #

Post to API with csrf token. See #postWithToken

Parameters:

Name Type Attributes Description
params Object

API parameters

ajaxOptions Object <optional>
Source:

Returns:

See #post

Type
jQuery.Promise
Post to API with csrf token.

postWithToken(tokenType, params, ajaxOptionsopt) → {jQuery.Promise} #

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:

See post()

Type
jQuery.Promise
Post to API with the specified type of token.

rollback(page, user, paramsopt) → {jQuery.Promise} #

Convenience method for action=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
Convenience method for action=rollback.

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

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

Parameters:

Name Type Description
name string
value string | null
Source:

Returns:

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

saveOptions(options) → {jQuery.Promise} #

Asynchronously save the values of user options using the Options API.

If a value of null 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 promise is always returned that will be resolved when all requests complete.

If a request from a previous saveOptions() call is still pending, this will wait for it to be completed, otherwise MediaWiki gets sad. No requests are sent for anonymous users, as they would fail anyway. See T214963.

Parameters:

Name Type Description
options Object

Options as a { name: value, … } object

Source:

Returns:

Type
jQuery.Promise

Asynchronously save the values of user options using the Options API.

unwatch(pages) → {jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>} #

Convenience method for action=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 an array thereof. If an array is passed, the return value passed to the promise will also be an array of appropriate objects.

Source:

Returns:

A promise that resolves with an object (or array of objects) describing each page that was passed in and its current watched/unwatched status.

Type
jQuery.Promise.<(mw.Api.WatchedPage|Array.<mw.Api.WatchedPage>)>
Convenience method for 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 inside of it, or a File object.

data Object

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:

Name Type Description
filekey string
data Object
Source:

Returns:

Type
jQuery.Promise
Finish an upload in the stash.

uploadToStash(file, dataopt) → {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 function to finish the stash upload. You can call that function with an argument containing more, or conflicting, data to pass to the server.

Example

// upload a file to the stash with a placeholder filename
api.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 a function that should be called to finish the upload.

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

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

Convenience method for action=watch.

Parameters:

Name Type Attributes Description
pages string | mw.Title | Array.<string> | Array.<mw.Title>

Full page name or instance of mw.Title, or an array thereof. If an array is passed, the return value passed to the promise will also be an array of appropriate objects.

expiry string <optional>

When the page should expire from the watchlist. If omitted, the page will not expire.

Since:
  • 1.35 - expiry parameter can be passed when Watchlist Expiry is enabled
Source:

Returns:

A promise that resolves with an object (or array of objects) describing each page that was passed in and its current watched/unwatched status.

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

Type Definitions

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

Parameters:

Name Type Description
revision Object

Current revision

Properties
Name Type Description
content string

Current revision content

Source:

Returns:

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

Type
string | Object | jQuery.Promise

Options #

Type:

  • Object

Properties:

Name Type Attributes Default Description
parameters Object <optional>
{ action: 'query', format: 'json' }

Default query parameters 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-valued parameters (since 1.28). Default is true if ajax.url is not set, false otherwise for compatibility.

Source:

UserInfo #

Type:

  • Object

Properties:

Name Type Description
groups Array.<string>

User groups that the current user belongs to

rights Array.<string>

Current user's rights

Source:

WatchedPage #

Type:

  • Object

Properties:

Name Type Description
title string

Full page name

watched boolean

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

Source: