API:Options
This page is part of the MediaWiki Action API documentation. |
MediaWiki version: | ≥ 1.20 |
POST request to change preferences of the current user.
API documentation
Example
Making any POST request is a multi-step process:
- Log in, via one of the methods described on API:Login .
- Get an Edit token .
- Send a POST request, with the CSRF token, to take action on a page.
The sample code below covers the final step in detail.
POST request
In this example, all parameters are passed in a GET request for the sake of simplicity. However, action=options requires POST requests; GET requests will cause an error.
Changing three options
api.php? action=options& token=58b54e0bab4a1d3fd3f7653af38e75cb%2B\& change=hideminor=1|skin=vector& optionname=nickname& optionvalue=custom-signa|ture [try in ApiSandbox]
Result |
---|
<?xml version="1.0" encoding="utf-8"?>
<api options="success" />
|
Response
{
"options": "success"
}
Sample code
Python
#!/usr/bin/python3
"""
change_user_options.py
MediaWiki API Demos
Demo of `Options` module: POST request to change three options
for current user
MIT license
"""
import requests
S = requests.Session()
URL = "https://test.wikipedia.org/w/api.php"
# Step 1: GET request to fetch login token
PARAMS_0 = {
"action": "query",
"meta": "tokens",
"type": "login",
"format": "json"
}
R = S.get(url=URL, params=PARAMS_0)
DATA = R.json()
LOGIN_TOKEN = DATA['query']['tokens']['logintoken']
# Step 2: POST request to log in. Use of main account for login is not
# supported. Obtain credentials via Special:BotPasswords
# (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
PARAMS_1 = {
"action": "login",
"lgname": "bot_user_name",
"lgpassword": "bot_password",
"lgtoken": LOGIN_TOKEN,
"format": "json"
}
R = S.post(URL, data=PARAMS_1)
# Step 3: GET request to fetch CSRF token
PARAMS_2 = {
"action": "query",
"meta": "tokens",
"format": "json"
}
R = S.get(url=URL, params=PARAMS_2)
DATA = R.json()
CSRF_TOKEN = DATA['query']['tokens']['csrftoken']
# Step 4: POST request to change user options
# You can check out the large list of options you can change
# at https://www.mediawiki.org/wiki/API:Options
PARAMS_3 = {
"action": "options",
"format": "json",
"token": CSRF_TOKEN,
"change": "language=en|skin=vector",
"optionname": "nickname",
"optionvalue": "custom-signa|ture"
}
R = S.post(URL, data=PARAMS_3)
DATA = R.json()
print(DATA)
PHP
<?php
/*
change_user_options.php
MediaWiki API Demos
Demo of `Options` module: POST request to change three options
for current user
MIT license
*/
$endPoint = "https://test.wikipedia.org/w/api.php";
$login_Token = getLoginToken(); // Step 1
loginRequest( $login_Token ); // Step 2
$csrf_Token = getCSRFToken(); // Step 3
change_options( $csrf_Token ); // Step 4
// Step 1: GET request to fetch login token
function getLoginToken() {
global $endPoint;
$params1 = [
"action" => "query",
"meta" => "tokens",
"type" => "login",
"format" => "json"
];
$url = $endPoint . "?" . http_build_query( $params1 );
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );
$output = curl_exec( $ch );
curl_close( $ch );
$result = json_decode( $output, true );
return $result["query"]["tokens"]["logintoken"];
}
// Step 2: POST request to log in. Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest( $logintoken ) {
global $endPoint;
$params2 = [
"action" => "login",
"lgname" => "bot_user_name",
"lgpassword" => "bot_password",
"lgtoken" => $logintoken,
"format" => "json"
];
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $endPoint );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params2 ) );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );
$output = curl_exec( $ch );
curl_close( $ch );
}
// Step 3: GET request to fetch CSRF token
function getCSRFToken() {
global $endPoint;
$params3 = [
"action" => "query",
"meta" => "tokens",
"format" => "json"
];
$url = $endPoint . "?" . http_build_query( $params3 );
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );
$output = curl_exec( $ch );
curl_close( $ch );
$result = json_decode( $output, true );
return $result["query"]["tokens"]["csrftoken"];
}
// Step 4: POST request to edit a page
function change_options( $csrftoken ) {
global $endPoint;
$params4 = [
"action" => "options",
"change" => "language=en|skin=timeless",
"optionname" => "nickname",
"optionvalue" => "custom-signa|ture",
"token" => $csrftoken,
"format" => "json"
];
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $endPoint );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params4 ) );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );
$output = curl_exec( $ch );
curl_close( $ch );
echo ( $output );
}
JavaScript
/*
change_user_options.js
MediaWiki API Demos
Demo of `Options` module: POST request to change two options
for current user
MIT license
*/
var request = require('request').defaults({jar: true}),
url = "https://test.wikipedia.org/w/api.php";
// Step 1: GET request to fetch login token
function getLoginToken() {
var params_0 = {
action: "query",
meta: "tokens",
type: "login",
format: "json"
};
request.get({ url: url, qs: params_0 }, function (error, res, body) {
if (error) {
return;
}
var data = JSON.parse(body);
loginRequest(data.query.tokens.logintoken);
});
}
// Step 2: POST request to log in.
// Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest(login_token) {
var params_1 = {
action: "login",
lgname: "bot_username",
lgpassword: "bot_password",
lgtoken: login_token,
format: "json"
};
request.post({ url: url, form: params_1 }, function (error, res, body) {
if (error) {
return;
}
getCsrfToken();
});
}
// Step 3: GET request to fetch CSRF token
function getCsrfToken() {
var params_2 = {
action: "query",
meta: "tokens",
format: "json"
};
request.get({ url: url, qs: params_2 }, function(error, res, body) {
if (error) {
return;
}
var data = JSON.parse(body);
change_options(data.query.tokens.csrftoken);
});
}
// Step 4: POST request to change the user options
function change_options(csrf_token) {
var params_3 = {
action: "options",
change: "language=en|skin=timeless",
token: csrf_token,
format: "json"
};
request.post({ url: url, form: params_3 }, function (error, res, body) {
if (error) {
return;
}
console.log(body);
});
}
// Start From Step 1
getLoginToken();
MediaWiki JS
/*
change_user_options.js
MediaWiki API Demos
Demo of `Options` module: POST request to change three options
for current user
MIT License
*/
var params = {
action: 'options',
change: 'language=en|skin=monobook',
optionname: 'nickname',
optionvalue: 'custom-signa|ture',
format: 'json'
},
api = new mw.Api();
api.postWithToken( 'csrf', params ).done( function ( data ) {
console.log( data );
} );
Available options
The following is an example list obtained with
/w/api.php?action=query&format=json&meta=userinfo&uiprop=options
for a English Wikipedia, MediaWiki 1.40.0-wmf.14 (c526317) (December 2022) account. Most of the options listed here are defined by various MediaWiki extensions, like Echo , VisualEditor , WikiLove , or Gadgets or GrowthExperiments , among others.*
enotifusertalkpages
: 0
vector-limited-width
: 1vector-page-tools-pinned
: 1flaggedrevssimpleui
: 1flaggedrevsstable
: 0flaggedrevseditdiffs
: Trueflaggedrevsviewdiffs
: Falseflaggedrevswatch
: Falseglobaluserpage
: Truercenhancedfilters-seen-highlight-button-counter
: 0advancedsearch-disable
: Falseusebetatoolbar
: 1wikieditor-realtimepreview
: 0usecodemirror
: 0betafeatures-auto-enroll
: Falsepopupsreferencepreviews
: 0popups-reference-previews
: 0visualeditor-autodisable
: 0visualeditor-betatempdisable
: 0visualeditor-editor
: wikitextvisualeditor-enable
: 1visualeditor-enable-experimental
: 0visualeditor-enable-language
: 0visualeditor-hidebetawelcome
: 0visualeditor-hidetabdialog
: 0visualeditor-newwikitext
: 0visualeditor-tabs
: remember-lastvisualeditor-visualdiffpage
: 0mobile-editor
:math
: mathmlecho-subscriptions-web-page-review
: Trueecho-subscriptions-email-page-review
: Falseecho-subscriptions-web-login-fail
: Trueecho-subscriptions-email-login-fail
: Trueecho-subscriptions-web-login-success
: Falseecho-subscriptions-email-login-success
: Trueecho-email-frequency
: 0echo-dont-email-read-notifications
: Falseecho-subscriptions-web-edit-thank
: Trueecho-subscriptions-email-edit-thank
: Falsediscussiontools-betaenable
: 0discussiontools-editmode
:discussiontools-newtopictool
: 1discussiontools-newtopictool-createpage
: 1discussiontools-replytool
: 1discussiontools-sourcemodetoolbar
: 1discussiontools-topicsubscription
: 1discussiontools-autotopicsub
: 0discussiontools-visualenhancements
: 1usecodeeditor
: 1revisionslider-disable
: Falsetwocolconflict-enabled
: 1eventlogging-display-web
: 0eventlogging-display-console
: 0uls-preferences
:compact-language-links
: 1echo-subscriptions-web-cx
: Truecx
: Falsecx-enable-entrypoints
: Truecx-entrypoint-fd-status
: notshowncx_campaign_newarticle_shown
: Falsercshowwikidata
: 0wlshowwikibase
: 0echo-subscriptions-web-oauth-owner
: Trueecho-subscriptions-email-oauth-owner
: Trueecho-subscriptions-web-oauth-admin
: Trueecho-subscriptions-email-oauth-admin
: Trueores-damaging-flag-rc
: FalseoresDamagingPref
: softrcOresDamagingPref
: softoresHighlight
: FalseoresRCHideNonDamaging
: FalseoresWatchlistHideNonDamaging
: Falseipinfo-use-agreement
: 0twl-notified
: Noneccmeonemails
: 0date
: defaultdiffonly
: 0disablemail
: 0editfont
: monospaceeditondblclick
: 0editsectiononrightclick
: 0email-allow-new-users
: 1enotifminoredits
: Falseenotifrevealaddr
: 0enotifwatchlistpages
: 0extendwatchlist
: 0fancysig
: 0forceeditsummary
: 0gender
: unknownhideminor
: 0hidepatrolled
: 0hidecategorization
: 1imagesize
: 2minordefault
: 0newpageshidepatrolled
: 0nickname
:pst-cssjs
: 1norollbackdiff
: 0previewonfirst
: 0previewontop
: 1rcdays
: 7rcenhancedfilters-disable
: 0rclimit
: 50search-match-redirect
: Truesearch-special-page
: Searchsearchlimit
: 20search-thumbnail-extra-namespaces
: Trueshowhiddencats
: Falseshownumberswatching
: 1showrollbackconfirmation
: 0skin
: vectorthumbsize
: 4underline
: 2uselivepreview
: 0usenewrc
: 0watchcreations
: Truewatchdefault
: 0watchdeletion
: 0watchuploads
: 1watchlistdays
: 3watchlisthideanons
: 0watchlisthidebots
: 0watchlisthideliu
: 0watchlisthideminor
: 0watchlisthideown
: 0watchlisthidepatrolled
: 0watchlisthidecategorization
: 1watchlistreloadautomatically
: 0watchlistunwatchlinks
: 0watchmoves
: 0watchrollback
: 0wlenhancedfilters-disable
: 0wllimit
: 250useeditwarning
: 1prefershttps
: 1requireemail
: 0skin-responsive
: 1wikilove-enabled
: 1echo-cross-wiki-notifications
: 1growthexperiments-addimage-desktop
: 1timecorrection
: System|0centralnotice-display-campaign-type-advocacy
: 1centralnotice-display-campaign-type-article-writing
: 1centralnotice-display-campaign-type-photography
: 1centralnotice-display-campaign-type-event
: 1centralnotice-display-campaign-type-fundraising
: 1centralnotice-display-campaign-type-governance
: 1centralnotice-display-campaign-type-maintenance
: 1centralnotice-display-campaign-type-special
: 1language
: envariant
: envariant-ban
: banvariant-en
: envariant-crh
: crhvariant-gan
: ganvariant-iu
: iuvariant-kk
: kkvariant-ku
: kuvariant-sh
: sh-latnvariant-shi
: shivariant-sr
: srvariant-tg
: tgvariant-tly
: tlyvariant-uz
: uzvariant-zh
: zhsearchNs0
: 1searchNs1
: 0searchNs2
: 0searchNs3
: 0searchNs4
: 0searchNs5
: 0searchNs6
: 0searchNs7
: 0searchNs8
: 0searchNs9
: 0searchNs10
: 0searchNs11
: 0searchNs12
: 0searchNs13
: 0searchNs14
: 0searchNs15
: 0searchNs100
: 0searchNs101
: 0searchNs118
: 0searchNs119
: 0searchNs710
: 0searchNs711
: 0searchNs828
: 0searchNs829
: 0searchNs2300
: 0searchNs2301
: 0searchNs2302
: 0searchNs2303
: 0multimediaviewer-enable
: 1mf_amc_optin
: 0gadget-modrollback
: 0gadget-confirmationRollback-mobile
: 1gadget-removeAccessKeys
: 0gadget-searchFocus
: 0gadget-GoogleTrans
: 0gadget-ImageAnnotator
: 0gadget-imagelinks
: 0gadget-Navigation_popups
: 0gadget-exlinks
: 0gadget-search-new-tab
: 0gadget-PrintOptions
: 0gadget-revisionjumper
: 0gadget-Twinkle
: 0gadget-HideCentralNotice
: 0gadget-ReferenceTooltips
: 1gadget-formWizard
: 1gadget-Prosesize
: 0gadget-find-archived-section
: 0gadget-geonotice
: 1gadget-watchlist-notice
: 1gadget-WatchlistBase
: 1gadget-WatchlistGreenIndicators
: 1gadget-WatchlistGreenIndicatorsMono
: 1gadget-WatchlistChangesBold
: 0gadget-SubtleUpdatemarker
: 1gadget-defaultsummaries
: 0gadget-citations
: 0gadget-DotsSyntaxHighlighter
: 0gadget-HotCat
: 0gadget-wikEdDiff
: 0gadget-ProveIt
: 0gadget-ProveIt-classic
: 0gadget-Shortdesc-helper
: 0gadget-wikEd
: 0gadget-afchelper
: 0gadget-charinsert
: 1gadget-legacyToolbar
: 0gadget-extra-toolbar-buttons
: 1gadget-refToolbar
: 1gadget-EditNoticesOnMobile
: 1gadget-edittop
: 0gadget-UTCLiveClock
: 0gadget-purgetab
: 0gadget-ExternalSearch
: 0gadget-CollapsibleNav
: 0gadget-MenuTabsToggle
: 0gadget-dropdown-menus
: 0gadget-CategoryAboveAll
: 0gadget-addsection-plus
: 0gadget-CommentsInLocalTime
: 0gadget-OldDiff
: 0gadget-NoAnimations
: 0gadget-disablesuggestions
: 0gadget-NoSmallFonts
: 0gadget-topalert
: 0gadget-metadata
: 0gadget-JustifyParagraphs
: 0gadget-righteditlinks
: 0gadget-PrettyLog
: 0gadget-switcher
: 1gadget-SidebarTranslate
: 0gadget-Blackskin
: 0gadget-dark-mode-toggle
: 0gadget-VectorClassic
: 0gadget-widensearch
: 0gadget-DisambiguationLinks
: 0gadget-markblocked
: 0gadget-responsiveContent
: 0gadget-responsiveContentTimeless
: 1gadget-HideInterwikiSearchResults
: 0gadget-XTools-ArticleInfo
: 0gadget-ShowMessageNames
: 0gadget-DebugMode
: 0gadget-contribsrange
: 0gadget-BugStatusUpdate
: 0gadget-RTRC
: 0gadget-script-installer
: 0gadget-XFDcloser
: 0gadget-mobile-sidebar
: 0gadget-addMe
: 0gadget-NewImageThumb
: 0gadget-StickyTableHeaders
: 0gadget-MobileMaps
: 0gadget-ShowJavascriptErrors
: 0gadget-PageDescriptions
: 0gadget-autonum
: 0gadget-wide-vector-2022
: 0gadget-dark-mode
: 0cirrussearch-pref-completion-profile
: fuzzypopups
: 0echo-email-format
: htmlecho-subscriptions-email-system
: Trueecho-subscriptions-web-system
: Trueecho-subscriptions-push-system
: Trueecho-subscriptions-email-system-noemail
: Falseecho-subscriptions-web-system-noemail
: Trueecho-subscriptions-push-system-noemail
: Trueecho-subscriptions-email-system-emailonly
: Falseecho-subscriptions-web-system-emailonly
: Trueecho-subscriptions-push-system-emailonly
: Trueecho-subscriptions-email-user-rights
: Trueecho-subscriptions-web-user-rights
: Trueecho-subscriptions-push-user-rights
: Trueecho-subscriptions-email-other
: Falseecho-subscriptions-web-other
: Trueecho-subscriptions-push-other
: Trueecho-subscriptions-email-edit-user-talk
: 0echo-subscriptions-web-edit-user-talk
: Trueecho-subscriptions-push-edit-user-talk
: Trueecho-subscriptions-email-reverted
: Falseecho-subscriptions-web-reverted
: Trueecho-subscriptions-push-reverted
: Trueecho-subscriptions-email-article-linked
: Falseecho-subscriptions-web-article-linked
: Falseecho-subscriptions-push-article-linked
: Falseecho-subscriptions-email-mention
: Falseecho-subscriptions-web-mention
: Trueecho-subscriptions-push-mention
: Trueecho-subscriptions-email-mention-failure
: Falseecho-subscriptions-web-mention-failure
: Falseecho-subscriptions-push-mention-failure
: Falseecho-subscriptions-email-mention-success
: Falseecho-subscriptions-web-mention-success
: Falseecho-subscriptions-push-mention-success
: Falseecho-subscriptions-email-emailuser
: Falseecho-subscriptions-web-emailuser
: Trueecho-subscriptions-push-emailuser
: Trueecho-subscriptions-email-thank-you-edit
: Falseecho-subscriptions-web-thank-you-edit
: Trueecho-subscriptions-push-thank-you-edit
: Trueecho-subscriptions-push-page-review
: Trueecho-subscriptions-push-login-fail
: Trueecho-subscriptions-push-login-success
: Trueecho-subscriptions-push-edit-thank
: Trueecho-subscriptions-email-dt-subscription
: Falseecho-subscriptions-web-dt-subscription
: Trueecho-subscriptions-push-dt-subscription
: Trueecho-subscriptions-email-dt-subscription-archiving
: Falseecho-subscriptions-web-dt-subscription-archiving
: Trueecho-subscriptions-push-dt-subscription-archiving
: Trueecho-subscriptions-email-cx
: Falseecho-subscriptions-push-cx
: Trueecho-subscriptions-email-ge-mentorship
: Falseecho-subscriptions-web-ge-mentorship
: Trueecho-subscriptions-push-ge-mentorship
: Trueecho-subscriptions-email-wikibase-action
: Falseecho-subscriptions-web-wikibase-action
: Trueecho-subscriptions-push-wikibase-action
: Truegrowthexperiments-help-panel-tog-help-panel
: Falsehomepage_mobile_discovery_notice_seen
: Truegrowthexperiments-homepage-suggestededits-guidance-blue-dot
: {"vector":{"link-recommendation":true,"image-recommendation":true},"minerva":{"link-recommendation":true,"image-recommendation":true}}growthexperiments-homepage-se-topic-filters-mode
: ORgrowthexperiments-homepage-enable
: Falsegrowthexperiments-homepage-pt-link
: Falsegrowthexperiments-tour-help-panel
: Truegrowthexperiments-tour-homepage-mentorship
: Truegrowthexperiments-tour-homepage-welcome
: Truegrowthexperiments-tour-homepage-discovery
: Truegrowthexperiments-tour-newimpact-discovery
: Falsegrowthexperiments-starred-mentees
:growthexperiments-mentor-dashboard-seen
: 0growthexperiments-mentor-dashboard-last-update
: Nonegrowthexperiments-mentee-overview-presets
: {"usersToShow":10,"filters":{"minedits":1,"maxedits":500}}growthexperiments-homepage-mentorship-enabled
: 1growthexperiments-mentorship-weight
: 2
Possible errors
In addition to the usual stuff :
Code | Info |
---|---|
notloggedin | Anonymous users cannot change preferences |
nochanges | No changes were requested. |
Parameter history
- 1.21: Introduced
resetkinds
Additional notes
- This API is primarily intended for changing options which are registered by MediaWiki core or extensions and available on Special:Preferences.
- You can also use the API to set arbitrary user options that can be used by user scripts or external editors. These options must begin with the prefix
userjs-
. - There is currently no limit on the number of user options you can set at once. You can store data within a user option by encoding it as a
JSON
string. - Providing only names of options without equal sign results in resetting them (e.g.
hideminor|skin
). In the case of an arbitraryuserjs-
key/value pair, the resetting results in its deletion. - The
change
parameter cannot be used to set a value which contains a pipe character|
, as it is used by the API to separate options. If you need to set such a value (e.g., a user signature) use anoptionname
&optionvalue
pair. - The following limits apply to all user options:
- The byte length of the key must be <= 255.
- The byte length of the value must be <= 65535.
- The key must consist only of ASCII letters, numbers, hyphens and underscores (a-z, A-Z, 0-9, _, -).
See also
- API:Userinfo - for reading existing options.