From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page API:Edit and the translation is 35% complete.

Other languages:
Deutsch • ‎English • ‎Tiếng Việt • ‎dansk • ‎español • ‎français • ‎polski • ‎русский • ‎тоҷикӣ • ‎中文 • ‎日本語
MediaWiki版本: 1.13

编辑一个页面时会进行POST 请求



(main | 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 of the page to edit. Cannot be used together with pageid.


Page ID of the page to edit. Cannot be used together with title.

Type: integer

Section number. 0 for the top section, new for a new section.


The title for a new section.


Page content.


Edit summary. Also section title when section=new and sectiontitle is not set.


Change tags to apply to the revision.

Values (separate with | or alternative):

Mark this edit as a minor edit.

Type: boolean (details)

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)

Mark this edit as a bot edit.

Type: boolean (details)

Timestamp of the base revision, used to detect edit conflicts. May be obtained through action=query&prop=revisions&rvprop=timestamp.

Type: timestamp (allowed formats)

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)

Override any errors about the page having been deleted in the meantime.

Type: boolean (details)

Don't edit the page if it exists already.

Type: boolean (details)

Throw an error if the page doesn't exist.

Type: boolean (details)

Add the page to the current user's watchlist.

Type: boolean (details)

Remove the page from the current user's watchlist.

Type: boolean (details)

Unconditionally add or remove the page from the current user's watchlist, use preferences or do not change watch.

One of the following values: watch, unwatch, preferences, nochange
Default: preferences

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.


Add this text to the beginning of the page. Overrides text.


Add this text to the end of the page. Overrides text.

Use section=new to append a new section, rather than this parameter.


Undo this revision. Overrides text, prependtext and appendtext.

The value must be no less than 0.
Type: integer

Undo all revisions from undo to this one. If not set, just undo one revision.

The value must be no less than 0.
Type: integer

Automatically resolve redirects.

Type: boolean (details)

Content serialization format used for the input text.

One of the following values: application/json, text/css, text/plain, text/x-wiki, text/javascript

Content model of the new content.

One of the following values: GadgetDefinition, SecurePoll, sanitized-css, MassMessageListContent, flow-board, Scribunto, JsonSchema, NewsletterContent, wikitext, javascript, json, css, text

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.

Answer to the CAPTCHA


CAPTCHA ID from previous request


此示例中的示例代码使用Python。 有关示例请见API:Edit/Editing with Ajax ,响应请参阅Ajax



1. 使用API:登录 中描述的方法之一登录。 Note that while this is required to correctly attribute the edit to its author, many wikis do allow users to edit without registering or logging into an account.
2. GET a CSRF token :
3. Send a POST request, with the CSRF token, to take action on a page:

The Response section below is for the final POST request, to take action on the page. See the pages on API:登录 and API:令牌 for the intermediary JSON responses to earlier steps.

Also note that the tokens in the queries on this page are sample values. Actual tokens are unique to each login session and cross-site request. They are included only to demonstrate how to properly format queries.







    MediaWiki Action API Code Samples
    Demo of `Edit` module: POST request to edit a page
    Based on User:Александр Сигачёв, 
    MIT license

import requests

S = requests.Session()

URL = "https://test.wikipedia.org/w/api.php"

# Step 1: Retrieve a login token
PARAMS_1 = {
    "action": "query",
    "meta": "tokens",
    "type": "login",
    "format": "json"

R = S.get(url=URL, params=PARAMS_1)
DATA = R.json()

LOGIN_TOKEN = DATA["query"]["tokens"]["logintoken"]

# Step 2: Send a post request to log in. For this login 
# method, Obtain credentials by first visiting
# https://test.wikipedia.org/wiki/Special:BotPasswords/
# See https://www.mediawiki.org/wiki/API:Login for more
# information on log in methods.
PARAMS_2 = {
    "action": "login",
    "lgname": "user_name",
    "lgpassword": "password",
    "format": "json",
    "lgtoken": LOGIN_TOKEN

R = S.post(URL, data=PARAMS_2)

# Step 3: While logged in, retrieve a CSRF token
PARAMS_3 = {
    "action": "query",
    "meta": "tokens",
    "format": "json"

R = S.get(url=URL, params=PARAMS_3)
DATA = R.json()

CSRF_TOKEN = DATA["query"]["tokens"]["csrftoken"]

# Step 4: Send a post request to edit a page
PARAMS_4 = {
    "action": "edit",
    "title": "Sandbox",
    "format": "json",
    "appendtext": "Hello",
    "token": CSRF_TOKEN,

R = S.post(URL, data=PARAMS_4)
DATA = R.json()



The Python sample above is a basic implementation, of an edit request by a registered user. In real-world scenarios care should be taken to prevent edit conflicts. These occur when two or more users are attempting to edit the same page at the same time.

Conflicts can be prevented by retrieving the last revision timestamp when we request a CSRF token. Adding prop=info|revisions to the CSRF token request in Step 3 allows us to access the timestamp for the last revision. This timestamp will be used as the basetimestamp when we make our the edit request.

我们还需要我们开始编辑的准确时间 This can be retrieved by adding curtimestamp to the CSRF request as well. This value will serve as our starttimestamp.

Finally, in the actual edit request, set the basetimestamp and starttimestamp parameters, like so:


POST requests containing large amounts of text content (8000+ characters) should be sent with Content-Type: multipart/form-data indicated in the header. Because multipart/form-data does not need to add HTML escape characters (i.e., percent encoding) for spaces and punctuation, the amount of data passed will subsequently be much smaller than the percent-encoded equivalent.

However, there is still some overhead added by multipart/form-data -- roughly, 160 bytes per parameter. For short messages that don't require adding many escape characters, this amount of overhead can be inefficient, and percent-encoding is preferred[1].

Note that in our Python sample code, the request is percent-encoded by default.

See the MDN web docs for a more technical discussion of content-type and POST requests. See the Python Requests documentation for how to pass multipart/form-data using syntax similar to our Python sample code.


If the wiki you are targeting uses CAPTCHAs , your request may return an error containing an id number and a simple test, such as a question, a math problem, or an URL to an image. In order to complete your edit, you must complete the test, then retry your request with the id and the correct answer(s) appended to the original query string, like so: captchaid=sampleId&captchaword=answer

Other CAPTCHA systems and extensions may use different parameters for similar use. In general, use the field names for the id and test questions as the parameters in your second request.


代码 信息
notitle title参数必须被设置。
notext One of the text, appendtext, prependtext and undo parameters must be set
notoken token参数必须被设置。
invalidsection section参数必须为有效的章节ID或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 您尝试创建的条目已刚刚被创建。
noimageredirect-anon 匿名用户不能创建图片重定向。
noimageredirect 您没有权限创建图片重定向。
spamdetected 您的编辑被拒绝,因为它包含垃圾部分:Wikitext
filtered The filter callback function refused your edit
contenttoobig ⧼Apieror-contenttoobig⧽
noedit-anon 匿名用户不能编辑页面。
noedit 您没有权限编辑页面。
pagedeleted 在您取得页面时间戳以来,页面已被删除。
emptypage 不允许创建新的,空白的页面。
emptynewsection 无法创建空白新章节。
editconflict Edit conflict detected
revwrongpage rrevid不是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 edit模块需要POST请求。
readapidenied 您需要读取权限以使用此模块。
writeapidenied 您不被允许通过API编辑此wiki。
noapiwrite 通过API编辑此wiki已禁用。请确保$wgEnableWriteAPI=true;声明包含在wiki的LocalSettings.php文件中。
badtoken 无效的CSRF令牌。
missingparam title, pageid参数必须被设置。
invalidparammix 参数title, pageid不能一起使用。
invalidtitle 错误标题“title”。
nosuchpageid 没有ID为pageid的页面。
pagecannotexist 名字空间不允许实际页面。
nosuchrevid 没有ID为undo的修订版本。
nosuchrevid 没有ID为undoafter的修订版本。
undofailure Undo failed due to conflicting intermediate edits
badmd5 提供的MD5哈希不正确。
hookaborted 您尝试的修改被扩展程序中止。
parseerror Failed to parse the given text.
summaryrequired Summary required
blocked 您已被封禁,不能编辑。
ratelimited 您已超过您的速率限制。请等待一段时间再试。
unknownerror 未知错误:“retval”。
nosuchsection 没有章节$1。
sectionsnotsupported 内容模型$1不支持章节。
editnotsupported Editing of this type of page is not supported using the text based edit API.
appendnotsupported 不能使用内容模型$1附加在页面上。
redirect-appendonly 您试图使用重定向跟随模式编辑,而这必须与section=newprependtextappendtext共同使用。
badformat 由$3使用的内容模型$2尚不支持请求的内容格式$1。
customcssprotected 您没有权限编辑此CSS页面,因为它包含另一位用户的个人设置。
customjsprotected 您没有权限编辑此JavaScript页面,因为它包含另一位用户的个人设置。
taggingnotallowed You don't have permission to set change tags
tpt-target-page 本页面无法手动更新。本页面是$1页面的翻译版,可以使用[$2 翻译工具]来更新该翻译。
When using Extension:Translate, editing of a translated subpage is not allowed.


  • v1.25: Introduced tags
  • v1.21: Introduced contentformat, contentmodel
  • v1.20: Introduced pageid
  • v1.19: Introduced sectiontitle
  • v1.18: Deprecated captchaid, captchaword
  • v1.17: Introduced redirect
  • v1.16: Deprecated watch, unwatch
  • v1.16: Introduced watchlist
  • v1.15: Introduced undo, undoafter
  • v1.14: Introduced starttimestamp


  • Log in is not strictly required by the API, but it is needed to correctly attribute the edit to its author. A successful edit from a user who is not logged in will be attributed to their IP address.
  • Bots that are not logged in may face restrictions on editing and other write requests; see Manual:Creating a bot#Logging in for more details.
  • Users who are not logged in will always be given the empty CSRF token, +\.
  • The process for requesting a token has changed several times across versions. 参见API:令牌 以获取更多信息。
  • ResourceLoader provides a way to access edit tokens when running code within a wiki page.
  • You can use the same login token for all edit operations across the same wiki, during a single login session.
  • It is a good practice to pass any tokens in your request at the end of the query string, or at least after the text parameter. That way, if the connection is interrupted, the token will not be passed and the edit will fail. If you are using the mw.Api object to make requests, this is done automatically.
  • Although captchaid and captchaword have, technically, been removed from API:Edit since v1.18, Extension:ConfirmEdit extends API:Edit to work with CAPTCHAs. Thus, with ConfirmEdit installed, these parameters are still available. ConfirmEdit comes packaged with the MediaWiki software, v1.18+.