API:Редагування

This page is a translated version of the page API:Edit and the translation is 77% complete.
Версія MediaWiki:
1.13

POST-запит на редагування сторінки.

Документація API


action=edit

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

Specific parameters:
Other general parameters are available.
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.

tags

Change tags to apply to the revision.

Values (separate with | or alternative): convenient-discussions, possible vandalism, repeating characters
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: 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

Приклад

Зразок коду в цьому прикладі на мові Python. Див. API:Edit/Editing with Ajax для прикладів та відповідей у ​​Ajax .

Запит POST

Внесення змін та, фактично, будь-який запит POST — це багакроковий процес.

1. Увійдіть, використовуючи один із методів, описаних у API:Вхід . Зауважте, що хоча це потрібно для правильного приписування редагування його автору, багато вікі дозволяють користувачам редагувати без реєстрації та входу в обліковий запис.
2. GET токен CSRF :


3. Надішліть запит POST із токеном CSRF, щоб виконати дії на сторінці:


Розділ «Відповідь» нижче призначений для остаточного запиту POST, щоб виконати дію на сторінці. Див. сторінки на API:Вхід і API:Токени для відповідей за посередництвом JSON на попередні кроки.

Також зверніть увагу, що токени у запитах на цій сторінці мають зразкові значення. Чинні токени унікальні для кожного сеансу входу та міжсайтового запиту. Вони включені лише для демонстрації правильного форматування запитів.

Відповідь

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

Конфлікти редагувань

Приклад на Python є базовою реалізацією запиту на редагування зареєстрованим користувачем. 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:



Великі редагування

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.

Можливі помилки

Код Інформація
notitle Параметр title має бути заповнений.
missingparam Щонайменше один параметрів text, appendtext та undo є обов'язковим.
notoken Параметр token має бути заповнений.
invalidsection Параметр section має бути дійсним ідентифікатором розділу або new.
protectedpage Ця сторінка захищена від редагування та інших дій.
cantcreate У вас нема дозволу створювати нові сторінки.
cantcreate-anon Анонімні користувачі не можуть створювати нові сторінки
articleexists Сторінку, яку ви намагалися створити, вже було створено.
noimageredirect-anon Анонімні користувачі не можуть створювати перенаправлення на файли.
noimageredirect Ви не маєте прав на створення перенаправлень на файли.
spamdetected Ваше редагування було відхилено, оскільки воно містило фрагмент спаму: Wikitext.
abusefilter-warning Цю дію було автоматично визначено як шкідливу.
abusefilter-disallowed Цю дію було автоматично визначено як шкідливу, а тому заборонено.
contenttoobig Наданий вами вміст перевищує ліміт у bytes кібібайтів розміру сторінки.
Where bytes is the value of $wgMaxArticleSize .
noedit-anon Анонімні користувачі не можуть редагувати сторінки.
noedit У Вас немає прав на редагування сторінок.
pagedeleted Цю сторінку було вилучено після того, як Ви отримали її мітку часу.
emptypage Створення нових порожніх сторінок недозволене.
emptynewsection Створення нових порожніх розділів неможливе.
editconflict Конфлікт редагувань.
revwrongpage rrevid не є версією сторінки pagename.
Відкидається, якщо для undo або undoafter надано недійсну версію
undofailure Неможливо скасувати редагування через несумісність проміжних змін.
missingtitle Вказана Вами сторінка не існує.
(див. вище nocreate параметр)
mustbeposted Модуль edit потребує запиту POST.
readapidenied Вам потрібне право на читання, щоб використовувати цей модуль.
writeapidenied Ви не маєте дозволу на редагування цієї вікі через API.
noapiwrite Редагування цієї вікі через API вимкнено.
badtoken Недійсний токен CSRF.
missingparam Параметр title, pageid має бути заповнений.
invalidparammix Ці параметри title, pageid не можна використовувати водночас.
invalidtitle Погана назва «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 Немає сторінки з ідентифікатором pageid.
pagecannotexist Простір назв не дозволяє фактичних сторінок.
nosuchrevid Немає версії з ідентифікатором undo.
nosuchrevid Немає версії з ідентифікатором undoafter.
badmd5 Вказаний хеш MD5 був неправильним.
hookaborted Зміну, що Ви намагалися зробити, відкинуто обробником.
parseerror Невдача серіалізації вмісту: parseerror
summaryrequired ⧼apierror-summaryrequired⧽
blocked Вам заблоковано можливість редагування.
ratelimited Ви перевищили свій ліміт частоти. Будь ласка, почекайте деякий час і спробуйте знову.
unknownerror Невідома помилка: «retval».
nosuchsection Немає розділу $1.
sectionsnotsupported Розділи не підтримуються для контентної моделі $1.
editnotsupported Редагування цього типу сторінок не підтримується за допомогою текстового API редагування.
appendnotsupported Не вдається додавати до сторінок, що використовують контентну модель $1.
redirect-appendonly Ви зробили спробу редагування з використанням режиму переходу за перенаправленням, який має використовуватись разом із section=new, prependtext, або appendtext.
edit-invalidredirect Неможливо відредагувати $1 при переході за перенаправленням, оскільки ціль $2 є недійсною.
badformat Запитуваний формат $1 не підтримується контентною моделлю $2, що використовується $3.
customcssprotected У вас немає дозволу на редагування цієї CSS-сторінки, бо вона містить особисті налаштування іншого користувача.
customjsprotected У вас немає дозволу на редагування цієї JavaScript-сторінки, бо вона містить особисті налаштування іншого користувача.
taggingnotallowed У вас немає дозволу встановлювати теги змін
badtags Мітку «Tag» не можна додавати вручну.
Такі мітки не можна додавати вручну: Tag1, Tag2
tpt-target-page Ця сторінка не може бути оновлена вручну.

Це – переклад сторінки $1 і його можна оновити за допомогою [$2 засобу перекладу].
При використанні Розширення:Переклад редагування перекладеної підсторінки не дозволяється.

Історія параметра

  • 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

Додаткові примітки

  • API не вимагає строго входу, але він необхідний для правильного приписування редагування своєму автору. Успішне редагування від користувача, який не ввійшов до системи, буде віднесено до його IP-адреси.
  • Боти, які не увійшли в систему, можуть стикатися з обмеженнями щодо редагування та інших запитів на запис; див. Посібник:Створення бота#Вхід , щоб отримати докладнішу інформацію.
  • Користувачам, які не ввійшли в систему, завжди буде видано порожній токен CSRF, +\.
  • Процес запиту токена змінювався кілька разів у різних версіях. Докладніше див. API:Токени .
  • ResourceLoader забезпечує спосіб доступу до токенів редагування під час запуску коду на вікі-сторінці.
  • Ви можете використовувати один і той самий токен CSRF для всіх операцій редагування в одній і тій самій вікі під час одного сеансу входу.
  • Це хороша практика — передавати будь-які токени у своєму запиті наприкінці рядка запиту або принаймні після текстового параметра. Таким чином, якщо з'єднання перервано, токен не буде передано, а редагування не вдасться. Якщо для обробки запитів ви використовуєте об’єкт mw.Api , це робиться автоматично.
  • Незважаючи на те, що captchaid та captchaword технічно були вилучені з API:Редагування з версії 1.18, Extension:ConfirmEdit розширює API:Редагування для роботи з CAPTCHA. Таким чином, якщо встановлено ConfirmEdit, ці параметри все ще доступні. ConfirmEdit поставляється в комплекті з програмним забезпеченням MediaWiki v1.18+.

Див. також

  • Довідка:Редагування - містить корисні посилання на редагування статей.
  • Manual:Bot passwords - описує, як увійти в систему за допомогою спрощеного інтерфейсу під час доступу до вікі через скрипт або програму, а не через графічний інтерфейс GUI.
  • Manual:Creating a bot - докладніше про використання бота для автоматичного редагування сторінок.
  • ResourceLoader - забезпечує спосіб доступу до токенів редагування під час запуску JavaScript на сторінці MediaWiki.
  • API:Токени - містить докладнішу інформацію про використання токенів для входу або надсилання запитів POST.
  • API:Tokens (action) - застарілий API, відмінний від API:Токени , для запиту токенів у попередніх версіях MediaWiki.
  • API:Compare - дозволяє визначати різницю між редагуваннями на сторінці.
  • API:Managetags - змінює теги на сторінці.
  • API:Відкіт - скасовує ряд змін.
  • API:Filerevert - відкочує файли до попереднього стану.
  • API:Revisiondelete - видаляє та відновлює версії на сторінці.


Посилання