API:Edit

From MediaWiki.org
Jump to: navigation, search
Tools clipart.png This page is part of the MediaWiki API documentation.
Language: English  • Deutsch • español • français • 日本語 • Tiếng Việt
MediaWiki API

Quick overview:

v · d · e
MediaWiki version: 1.13

Requires the selected MediaWiki to have the following configuration settings set to true: $wgEnableAPI and $wgEnableWriteAPI. See Manual:DefaultSettings.php.

Contents

[edit] Token

To edit a page, an edit token is required. This token is the same for all pages, but changes at every login. If you want to protect against edit conflicts (which is wise), you also need to get the timestamp of the last revision. You can obtain these as follows: Obtaining an edit token

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

[edit] Editing pages

Pages can be edited and created with action=edit.

[edit] Parameters

Some of these parameters seem to be revised in v1.20; for the current list, see ApiEditPage::getAllowedParams(). To see the parameter list currently in use at Wikipedia, see:
  • title: Page to edit. Cannot be used together with pageid.
  • pageid: Page ID of the page to edit. Cannot be used together with title.
  • section: nth section to edit. Use 0 for the top section, 'new' for a new section. Omit if replacing the entire page
  • sectiontitle: Title to use if creating a new section. If not specified, summary will be used instead MW 1.19+
  • text: New page (or section) content
  • token: Edit token. Especially if you are not using the md5 parameter, the token should be sent as the last parameter, or at least, after the text parameter, to prevent a bad edit from getting committed if transmission of the body is interrupted for some reason.
  • summary: Edit comment
  • minor: If set to true, mark the edit as minor
  • notminor: If set to true, don't mark the edit as minor, even if you have the "Mark all my edits minor by default" preference enabled
  • bot: If set, mark the edit as bot; even if you are using a bot account the edits will not be marked unless you set this flag
  • basetimestamp: Timestamp of the last revision, used to detect edit conflicts. Leave unset to ignore conflicts
  • starttimestamp: Timestamp when you obtained the edit token. Used to detect edit conflicts. Leave unset and use recreate to ignore conflicts
  • recreate: If set, suppress errors about the page having been deleted in the meantime and recreate it [1]
  • createonly: If set, throw an error if the page already exists [1]
  • nocreate: If set, throw a missingtitle error if the page doesn't exist [1]
  • watchlist: Specify how the watchlist is affected by this edit, set to one of "watch", "unwatch", "preferences", "nochange":
    • watch: add the page to the watchlist
    • unwatch: remove the page from the watchlist
    • preferences: use the preference settings (Default)
    • nochange: don't change the watchlist
  • md5: MD5 hash (hex) of the text parameter. If this parameter is set and the hashes don't match, the edit is rejected. This can be used to guard against data corruption
  • captchaid: CAPTCHA ID from the previous request
  • captchaword: Answer to the CAPTCHA
  • undo: Revision ID to undo. Overrides text, prependtext and appendtext
  • undoafter: Undo all revisions from undo up to but not including this one. If not set, just undo one revision
  1. 1.0 1.1 1.2 The presence of this variable activates its feature. For instance adding the value "recreate" with or without a value will suppress errors about the page being previously deleted.

[edit] Example

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. Adding a new section to en:Talk:Main Page

<?xml version="1.0" encoding="utf-8"?>
<api>
  <edit result="Success" pageid="12" title="Talk:Main Page" oldrevid="465" newrevid="471" />
</api>

[edit] CAPTCHAs and extension errors

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>

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 errors using either the format described above or the usual error format.

[edit] Possible errors

In addition to the usual stuff:

  • code: notitle
    • info: The title parameter must be set
  • code: notext
    • info: One of the text, appendtext, prependtext and undo parameters must be set
  • code: notoken
    • info: The token parameter must be set
  • code: invalidsection
    • info: The section parameter must be set to an integer or 'new'
  • code: protectedtitle
    • info: This title has been protected from creation
  • code: cantcreate
    • info: You don't have permission to create new pages
  • code: cantcreate-anon
    • info: Anonymous users can't create new pages
  • code: articleexists
    • info: The article you tried to create has been created already
  • code: noimageredirect-anon
    • info: Anonymous users can't create image redirects
  • code: noimageredirect
    • info: You don't have permission to create image redirects
  • code: spamdetected
    • info: Your edit was refused because it contained a spam fragment: ``wikitext''
  • code: filtered
    • info: The filter callback function refused your edit
  • code: contenttoobig
    • info: The content you supplied exceeds the article size limit of bytes bytes
  • code: noedit-anon
    • info: Anonymous users can't edit pages
  • code: noedit
    • info: You don't have permission to edit pages
  • code: pagedeleted
    • info: The page has been deleted since you fetched its timestamp
  • code: emptypage
    • info: Creating new, empty pages is not allowed
  • code: emptynewsection
    • info: Creating empty new sections is not possible.
  • code: editconflict
    • info: Edit conflict detected
  • code: revwrongpage
    • info: rrevid is not a revision of ``pagename''
      • Thrown if an invalid revid is given for undo or undoafter
  • code: undo-failure
    • info: Undo failed due to conflicting intermediate edits
  • code: missingtitle

[edit] Editing via Ajax

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.' );
        }
    });
}

[edit] Large texts

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