API:Edit
This page is part of the MediaWiki Action API documentation. |
เวอร์ชันมีเดียวิกิ: | ≥ 1.13 |
POST request to edit a page.
API documentation
ตัวอย่าง
The sample code in this example is in Python.
See API:Edit/Editing with Ajax for examples and responses in Ajax .
POST request
Making edits, and, indeed, any POST request, is a multi-step process.
- 1. Log in, via one of the methods described in API:Login . 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 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:Login and API:Tokens 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.
Response
{
"edit": {
"result": "Success",
"pageid": 94542,
"title": "Wikipedia:Sandbox",
"contentmodel": "wikitext",
"oldrevid": 371705,
"newrevid": 371707,
"newtimestamp": "2018-12-18T16:59:42Z"
}
}
รหัสตัวอย่าง
Python
#!/usr/bin/python3
"""
edit.py
MediaWiki API Demos
Demo of `Edit` module: POST request to edit a page
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 edit a page
PARAMS_3 = {
"action": "edit",
"title": "Project:Sandbox",
"token": CSRF_TOKEN,
"format": "json",
"appendtext": "Hello"
}
R = S.post(URL, data=PARAMS_3)
DATA = R.json()
print(DATA)
PHP
<?php
/*
edit.php
MediaWiki API Demos
Demo of `Edit` module: POST request to edit a page
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
editRequest($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 editRequest( $csrftoken ) {
global $endPoint;
$params4 = [
"action" => "edit",
"title" => "Project:Sandbox",
"appendtext" => "Hello",
"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
/*
edit.js
MediaWiki API Demos
Demo of `Edit` module: POST request to edit a page
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);
editRequest(data.query.tokens.csrftoken);
});
}
// Step 4: POST request to edit a page
function editRequest(csrf_token) {
var params_3 = {
action: "edit",
title: "Project:Sandbox",
appendtext: "test edit",
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
/*
edit.js
MediaWiki API Demos
Demo of `Edit` module: POST request to edit a page
MIT License
*/
var params = {
action: 'edit',
title: 'Project:Sandbox',
appendtext: 'Hello',
format: 'json'
},
api = new mw.Api();
api.postWithToken( 'csrf', params ).done( function ( data ) {
console.log( data );
} );
User cases
Edit conflicts
The Python sample 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.
We also need the exact time when we start our edit.
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:
Large edits
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.
CAPTCHAs
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.
ข้อบกพร่อง (error) ที่อาจเกิด
รหัส (Code) | ข้อมูล (Info) |
---|---|
notitle | The title parameter must be set. |
missingparam | At least one of the parameters text, appendtext และ undo is required. |
notoken | The token parameter must be set. |
invalidsection | The section parameter must be a valid section ID or new. |
protectedpage | หน้านี้ถูกล็อกเพื่อป้องกันการแก้ไขหรือปฏิบัติการอื่น |
cantcreate | คุณไม่มีสิทธิสร้างหน้าใหม่ |
cantcreate-anon | Anonymous users can't create new pages |
articleexists | The page 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 .
|
abusefilter-warning | This action has been automatically identified as harmful. |
abusefilter-disallowed | This action has been automatically identified as harmful, and therefore disallowed. |
contenttoobig | The content you supplied exceeds the page size limit of bytes kibibytes. Where bytes is the value of $wgMaxArticleSize . |
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 | แก้ไขชนกัน |
revwrongpage | rrevid is not a revision of pagename. Thrown if an invalid revid is given for undo or undoafter
|
undofailure | การแก้ไขนี้ไม่สามารถย้อนกลับได้ เนื่องจากขัดแย้งกับการแก้ไขระหว่างกลาง |
missingtitle | The page you specified doesn't exist. (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. |
badtoken | Invalid CSRF token. |
missingparam | The title, pageid parameter must be set. |
invalidparammix | The parameters title, pageid can not be used together. |
invalidtitle | Bad title "title". |
invalid-content-data | ข้อมูลเนื้อหาไม่ถูกต้อง occurs when trying to edit a JSON page with non-conforming data, or while trying to edit a MassMessageListContent page |
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. |
badmd5 | The supplied MD5 hash was incorrect. |
hookaborted | สิ่งที่คุณพยายามดัดแปรเปลี่ยนถูกส่วนขยายยกเลิก |
parseerror | Content serialization failed: parseerror |
summaryrequired | ⧼apierror-summaryrequired⧽ |
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 section $1. |
sectionsnotsupported | Sections are not supported for content model $1. |
editnotsupported | Editing of this type of page is not supported using the text based edit API. |
appendnotsupported | Can't append to pages using content model $1. |
redirect-appendonly | You have attempted to edit using the redirect-following mode, which must be used in conjunction with section=new, prependtext, or appendtext. |
edit-invalidredirect | Cannot edit $1 while following redirects, as target $2 is not valid. |
badformat | The requested format $1 is not supported for content model $2 used by $3. |
customcssprotected | คุณไม่มีสิทธิแก้ไขหน้า CSS นี้ เพราะมีการตั้งค่าส่วนบุคคลของผู้ใช้อื่น |
customjsprotected | คุณไม่มีสิทธิแก้ไขหน้าจาวาสคริปต์นี้ เพราะหน้านี้มีการตั้งค่าส่วนบุคคลของผู้ใช้อื่น |
taggingnotallowed | You don't have permission to set change tags |
badtags | ไม่อนุญาตให้ใช้ป้ายระบุ "Tag" ด้วยมือ ไม่อนุญาตให้ใช้ป้ายระบุต่อไปนี้ด้วยมือ: Tag1, Tag2 |
tpt-target-page | ไม่สามารถปรับปรุงหน้านี้ตามปกติได้
หน้านี้เป็นหน้าการแปลของหน้า $1 และสามารถปรับปรุงการแปลได้โดยใช้[$2 เครื่องมือการแปล] |
ประวัติพารามิเตอร์ (Parameter history)
- v1.35: Introduced
baserevid
- v1.25: เปิดตัว
tags
- v1.21: เปิดตัว
contentformat
,contentmodel
- v1.20: เปิดตัว
pageid
- v1.19: เปิดตัว
sectiontitle
- v1.18: เลิกใช้
captchaid
,captchaword
- v1.17: เปิดตัว
redirect
- v1.16: เลิกใช้
watch
,unwatch
- v1.16: เปิดตัว
watchlist
- v1.15: เปิดตัว
undo
,undoafter
- v1.14: เปิดตัว
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.
See API:Tokens for more information.
- ResourceLoader provides a way to access edit tokens when running code within a wiki page.
- You can use the same CSRF 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
andcaptchaword
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+.
ดูเพิ่ม
- Help:Editing - contains useful links on editing articles.
- Manual:Bot passwords - describes how to log in using a simplified interface when accessing wikis via a script or application, rather than the GUI.
- Manual:Creating a bot - more details on using a bot to automatically edit pages.
- ResourceLoader - provides a way to access edit tokens when running JavaScript within a MediaWiki page.
- API:Tokens - has more details on using tokens to log in or make POST requests.
- API:Tokens (action) - a deprecated API, distinct from API:Tokens , for requesting tokens in earlier versions of MediaWiki.
- API:Compare - allows you to diff between edits on a page.
- API:Managetags - alters tags on a page.
- API:Rollback - reverts a series of edits.
- API:Filerevert - rolls back files to an earlier state.
- API:Revisiondelete - deletes and restores revisions to a page.