User:Cgt/Sandbox
MediaWiki version: | 1.13 |
Requires the selected MediaWiki to have the following configuration settings set to true
: $wgEnableAPI
and $wgEnableWriteAPI
. See Manual:DefaultSettings.php. This module is implemented by ApiEditPage.php.
Token
[edit]To edit a page, an edit token is required. This token is the same for all pages, but changes at every login. The preferred method to obtain an edit token depends on the MediaWiki version:
- Versions 1.24 and later: action=query&meta=tokens
- Versions 1.20-1.23: action=tokens
- Versions 1.19 and earlier: action=query&prop=info
Currently, all older methods continue to work, but are deprecated.
If you want to protect against edit conflicts (which is wise), you also need to get the timestamp of the last revision, included in the example below:
Result |
---|
<?xml version="1.0" encoding="utf-8"?>
<api>
<query>
<pages>
<page
pageid="15580374"
ns="0"
title="Main Page"
touched="2008-03-27T21:15:39Z"
lastrevid="199631190"
counter="0"
length="4712"
edittoken="000000000000000000+\">
<revisions>
<rev
revid="199631190"
user="David Levy"
timestamp="2008-03-20T17:26:39Z"
comment="Have you tested it in every major browser at every resolution." />
</revisions>
</page>
</pages>
</query>
</api>
|
When passing this to the Edit API, always pass the token parameter last (or at least after the text parameter). That way, if the edit gets interrupted, the token won't be passed and the edit will fail. This is done automatically by mw.Api.
When running on a MediaWiki page, the token can be obtained by calling mw.user.tokens.get('editToken')
(more information).
Editing pages
[edit]Pages can be edited and created with action=edit
.
The following documentation is the output of Special: |
action=edit
- This module requires read rights.
- This module requires write rights.
- This module only accepts POST requests.
- Source: MediaWiki
- License: GPL-2.0-or-later
Create and edit pages.
- title
Title of the page to edit. Cannot be used together with pageid.
- pageid
Page ID of the page to edit. Cannot be used together with title.
- Type: integer
- section
Section identifier. 0 for the top section, new for a new section. Often a positive integer, but can also be non-numeric.
- sectiontitle
The title for a new section when using section=new.
- text
Page content.
- summary
Edit summary.
When this parameter is not provided or empty, an edit summary may be generated automatically.
When using section=new and sectiontitle is not provided, the value of this parameter is used for the section title instead, and an edit summary is generated automatically.
Change tags to apply to the revision.
- Values (separate with | or alternative): AWB, convenient-discussions
- minor
Mark this edit as a minor edit.
- Type: boolean (details)
- notminor
Do not mark this edit as a minor edit even if the "Mark all edits minor by default" user preference is set.
- Type: boolean (details)
- bot
Mark this edit as a bot edit.
- Type: boolean (details)
- baserevid
ID of the base revision, used to detect edit conflicts. May be obtained through action=query&prop=revisions. Self-conflicts cause the edit to fail unless basetimestamp is set.
- Type: integer
- basetimestamp
Timestamp of the base revision, used to detect edit conflicts. May be obtained through action=query&prop=revisions&rvprop=timestamp. Self-conflicts are ignored.
- Type: timestamp (allowed formats)
- starttimestamp
Timestamp when the editing process began, used to detect edit conflicts. An appropriate value may be obtained using curtimestamp when beginning the edit process (e.g. when loading the page content to edit).
- Type: timestamp (allowed formats)
- recreate
Override any errors about the page having been deleted in the meantime.
- Type: boolean (details)
- createonly
Don't edit the page if it exists already.
- Type: boolean (details)
- nocreate
Throw an error if the page doesn't exist.
- Type: boolean (details)
- watch
- Deprecated.
Add the page to the current user's watchlist.
- Type: boolean (details)
- unwatch
- Deprecated.
Remove the page from the current user's watchlist.
- Type: boolean (details)
- watchlist
Unconditionally add or remove the page from the current user's watchlist, use preferences (ignored for bot users) or do not change watch.
- One of the following values: nochange, preferences, unwatch, watch
- Default: preferences
- watchlistexpiry
Watchlist expiry timestamp. Omit this parameter entirely to leave the current expiry unchanged.
- Type: expiry (details)
- md5
The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated. If set, the edit won't be done unless the hash is correct.
- prependtext
Add this text to the beginning of the page or section. Overrides text.
- appendtext
Add this text to the end of the page or section. Overrides text.
Use section=new to append a new section, rather than this parameter.
- undo
Undo this revision. Overrides text, prependtext and appendtext.
- Type: integer
- The value must be no less than 0.
- undoafter
Undo all revisions from undo to this one. If not set, just undo one revision.
- Type: integer
- The value must be no less than 0.
- redirect
Automatically resolve redirects.
- Type: boolean (details)
- contentformat
Content serialization format used for the input text.
- One of the following values: application/json, application/octet-stream, application/unknown, application/x-binary, text/css, text/javascript, text/plain, text/unknown, text/x-wiki, unknown/unknown
- contentmodel
Content model of the new content.
- One of the following values: Chart.JsonConfig, GadgetDefinition, Json.JsonConfig, JsonSchema, Map.JsonConfig, MassMessageListContent, NewsletterContent, Scribunto, SecurePoll, Tabular.JsonConfig, css, flow-board, javascript, json, sanitized-css, text, translate-messagebundle, unknown, wikitext
- token
A "csrf" token retrieved from action=query&meta=tokens
The token should always be sent as the last parameter, or at least after the text parameter.
- This parameter is required.
- returnto
Page title. If saving the edit created a temporary account, the API may respond with an URL that the client should visit to complete logging in. If this parameter is provided, the URL will redirect to the given page, instead of the page that was edited.
- Type: page title
- Accepts non-existent pages.
- returntoquery
URL query parameters (with leading ?). If saving the edit created a temporary account, the API may respond with an URL that the client should visit to complete logging in. If this parameter is provided, the URL will redirect to a page with the given query parameters.
- Default: (empty)
- returntoanchor
URL fragment (with leading #). If saving the edit created a temporary account, the API may respond with an URL that the client should visit to complete logging in. If this parameter is provided, the URL will redirect to a page with the given fragment.
- Default: (empty)
- captchaword
Answer to the CAPTCHA
- captchaid
CAPTCHA ID from previous request
- Edit a page.
- api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&baserevid=1234567&token=123ABC [open in sandbox]
- Prepend __NOTOC__ to a page.
- api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC [open in sandbox]
- Undo revisions 13579 through 13585 with autosummary.
- api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=2007-08-24T12:34:54Z&token=123ABC [open in sandbox]
Example
[edit]Note: In this example, all parameters are passed in a GET request just for the sake of simplicity. However, action=edit requires POST requests; GET requests will cause an error. Do not forget to set the Content-Type
header of your request to application/x-www-form-urlencoded
. The token that you received is terminated with +\
, this needs to be urlencoded (so it will end with %2B%5C
) before it is passed back.
Result |
---|
<?xml version="1.0" encoding="utf-8"?>
<api>
<edit result="Success" pageid="12" title="Talk:Main Page" oldrevid="465" newrevid="471" />
</api>
|
CAPTCHAs and extension errors
[edit]If an edit requires a CAPTCHA, you'll get something like:
<?xml version="1.0" encoding="utf-8"?>
<api>
<edit result="Failure">
<captcha type="math" mime="text/tex" id="509895952" question="36 + 4 = " />
</edit>
</api>
The specific information you get will depend on the captcha in use. In most cases, you won't get a math CAPTCHA, but a URL to an image (in the url
field). When you've solved the CAPTCHA, retry the request (in this case with captchaid=509895952&captchaword=40
).
Other extensions that use the APIEditBeforeSave hook may return failure results using either the format described above or the usual error format.
Possible errors
[edit]In addition to the usual stuff:
Code | Info |
---|---|
notitle | The title parameter must be set |
notext | One of the text, appendtext, prependtext and undo parameters must be set |
notoken | The token parameter must be set |
invalidsection | The section parameter must be set to an integer or 'new' |
protectedtitle | This title has been protected from creation |
cantcreate | You don't have permission to create new pages |
cantcreate-anon | Anonymous users can't create new pages |
articleexists | The article you tried to create has been created already |
noimageredirect-anon | Anonymous users can't create image redirects |
noimageredirect | You don't have permission to create image redirects |
spamdetected | Your edit was refused because it contained a spam fragment: "wikitext" |
filtered | The filter callback function refused your edit |
contenttoobig | The content you supplied exceeds the article size limit of bytes bytes |
noedit-anon | Anonymous users can't edit pages |
noedit | You don't have permission to edit pages |
pagedeleted | The page has been deleted since you fetched its timestamp |
emptypage | Creating new, empty pages is not allowed |
emptynewsection | Creating empty new sections is not possible. |
editconflict | Edit conflict detected |
revwrongpage | revid is not a revision of "pagename" Thrown if an invalid revid is given for undo or undoafter
|
undofailure | Undo failed due to conflicting intermediate edits |
missingtitle | (see above nocreate parameter)
|
mustbeposted | The edit module requires a POST request |
readapidenied | You need read permission to use this module |
writeapidenied | You're not allowed to edit this wiki through the API |
noapiwrite | Editing of this wiki through the API is disabled. Make sure the $wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file |
badtoken | Invalid token |
missingparam | One of the parameters title, pageid is required |
invalidparammix | The parameters title, pageid can not be used together |
invalidtitle | Bad title "title" |
nosuchpageid | There is no page with ID pageid |
pagecannotexist | Namespace doesn't allow actual pages |
nosuchrevid | There is no revision with ID undo |
nosuchrevid | There is no revision with ID undoafter |
undofailure | Undo failed due to conflicting intermediate edits |
badmd5 | The supplied MD5 hash was incorrect |
hookaborted | The modification you tried to make was aborted by an extension hook |
parseerror | Failed to parse the given text. |
summaryrequired | Summary required |
blocked | You have been blocked from editing |
ratelimited | You've exceeded your rate limit. Please wait some time and try again |
unknownerror | Unknown error: "retval" |
nosuchsection | There is no such section. |
sectionsnotsupported | Sections are not supported for this type of page. |
editnotsupported | Editing of this type of page is not supported using the text based edit API. |
appendnotsupported | This type of page can not be edited by appending or prepending text. |
redirect-appendonly | You have attempted to edit using the "redirect"-following mode, which must be used in conjuction with section=new, prependtext, or appendtext. |
badformat | The requested serialization format can not be applied to the page's content model |
customcssprotected | You're not allowed to edit custom CSS pages |
customjsprotected | You're not allowed to edit custom JavaScript pages |
Editing via Ajax
[edit]Below is sample code for editing a page via an Ajax request:
function addNewSection( summary, content, editToken ) {
$.ajax({
url: mw.util.wikiScript( 'api' ),
data: {
format: 'json',
action: 'edit',
title: mw.config.get( 'wgPageName' ),
section: 'new',
summary: summary,
text: content,
token: editToken
},
dataType: 'json',
type: 'POST',
success: function( data ) {
if ( data && data.edit && data.edit.result == 'Success' ) {
window.location.reload(); // reload page if edit was successful
} else if ( data && data.error ) {
alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
} else {
alert( 'Error: Unknown result from API.' );
}
},
error: function( xhr ) {
alert( 'Error: Request failed.' );
}
});
}
You can also use the mw.Api object:
var api = new mw.Api();
function addNewSection( summary, content ) {
api.postWithToken( "edit", {
action: "edit",
title: mw.config.get( "wgPageName" ),
section: "new",
summary: summary,
text: content
} ).done( function( result, jqXHR ) {
mw.log( "Saved successfully" );
location.reload();
} ).fail( function( code, result ) {
if ( code === "http" ) {
mw.log( "HTTP error: " + result.textStatus ); // result.xhr contains the jqXHR object
} else if ( code === "ok-but-empty" ) {
mw.log( "Got an empty response from the server" );
} else {
mw.log( "API error: " + code );
}
} );
}
Large texts
[edit]When using texts over 8000 characters, use "multipart/form-data" as it does not require escaping and will be significantly smaller than its urlencoded counterpart. Multipart has roughly 160 bytes of overhead for each parameter, so for seven parameters that's ~1.1kb overhead. Example:
POST http://en.wikipedia.org/w/api.php HTTP/1.1 User-Agent: Bot Framework Content-Type: multipart/form-data; boundary=---------------------------8ce61ec834cf268 Host: en.wikipedia.org Cookie: <removed> Content-Length: 1348 Accept-Encoding: gzip Connection: Keep-Alive -----------------------------8ce61ec834cf268 Content-Disposition: form-data; name="action" edit -----------------------------8ce61ec834cf268 Content-Disposition: form-data; name="title" Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Title here -----------------------------8ce61ec834cf268 Content-Disposition: form-data; name="text" Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Text here -----------------------------8ce61ec834cf268 Content-Disposition: form-data; name="summary" Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary -----------------------------8ce61ec834cf268 Content-Disposition: form-data; name="token" 1f287ba00a908e9622045e7b18ffa352+\ -----------------------------8ce61ec834cf268 Content-Disposition: form-data; name="assert" user -----------------------------8ce61ec834cf268 Content-Disposition: form-data; name="format" xml -----------------------------8ce61ec834cf268--