This page is a translated version of the page API:Edit and the translation is 54% complete.
Versão MediaWiki:
1.13

POST request para edita uma página.

Documentação da 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

Exemplo

O código de exemplo está na linguagem Python. Veja API:Edit/Editing with Ajax para exemplos e respostas em Ajax

Solicitação POST

Fazer edições, e qualquer requisição POST, é um processo de vários passos.

1. Entre através de um dos métodos descritos em API:Iniciar Sessão (autenticação/login) . Observe que, embora seja necessário atribuir corretamente a edição ao seu autor, muitos wikis permitem que os usuários editem sem se registrar ou fazer login em uma conta.
2. Obtenha o token CSRF .


3. Para executar uma ação em uma página, envie uma requisição POST com o token CSRF.


A seção Resposta abaixo é para a solicitação final do POST, para executar uma ação na página. Veja as páginas API:Iniciar Sessão (autenticação/login) e API:Tokens o código JSON de nível intermediário as respostas das etapas anteriores.

Observe também que os tokens nas consultas nesta página são valores de amostra. Os tokens reais são exclusivos para cada sessão de login e solicitação entre sites. Eles são incluídos apenas para demonstrar como formatar corretamente as consultas.

Resposta

{
    "edit": {
        "result": "Success",
        "pageid": 94542,
        "title": "Wikipedia:Sandbox",
        "contentmodel": "wikitext",
        "oldrevid": 371705,
        "newrevid": 371707,
        "newtimestamp": "2018-12-18T16:59:42Z"
    }
}

Exemplo de código

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

Casos de uso

Resolvendo conflitos

Este exemplo Python é uma implementação básica, de uma solicitação de edição por um usuário registrado. Nos cenários do mundo real, deve-se tomar cuidado para evitar conflitos de edição. Isso ocorre quando dois ou mais usuários estão tentando editar a mesma página ao mesmo tempo.

Os conflitos podem ser evitados recuperando o último registro de data e hora da revisão quando solicitamos um token CSRF. Adicione o código prop=info|revisions para à solicitação de token CSRF na Etapa 3 para permite acessar o registro de data e hora da última revisão. Esta etiqueta de data e hora será usado como basetimestamp quando fizermos a nossa solicitação de edição.

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:



Edições em massa

Solicitações POST contendo grandes quantidades de texto (acima de 8 000 caracteres) devem ser enviadas com Content-Type: multipart/form-data, conforme indicado em cabeçalho. 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.

Erros possíveis

Código Informação
notitle O parâmetro title precisa ser definido.
missingparam Ao menos um dos parâmetros text, appendtext e undo é necessário.
notoken O parâmetro token precisa ser definido.
invalidsection O parâmetro section deve ser um ID de seção válida ou new.
protectedpage Esta página foi protegida contra novas edições ou ações relacionadas.
cantcreate Você não possui permissão para criar novas páginas.
cantcreate-anon Anonymous users can't create new pages
articleexists O artigo que você tentou criar já foi criado.
noimageredirect-anon Os usuários anônimos não podem criar redirecionamentos de imagem.
noimageredirect Você não tem permissão para criar redirecionamentos de imagens.
spamdetected Sua edição foi bloqueada porque contem um fragmento de spam: 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 O conteúdo fornecido excede o limite de tamanho do artigo de bytes kibibyte.
Where bytes is the value of $wgMaxArticleSize .
noedit-anon Os usuários anônimos não podem editar páginas.
noedit Você não tem permissão para editar páginas.
pagedeleted A página foi excluída desde que você obteve seu timestamp.
emptypage Não é permitido criar páginas novas e vazias.
emptynewsection A criação de novas seções vazias não é possível.
editconflict Conflito de edição.
revwrongpage rrevid não é uma revisão de pagename.
Thrown if an invalid revid is given for undo or undoafter
undofailure A edição não pôde ser desfeita devido a alterações intermediárias conflitantes.
missingtitle A página que você especificou não existe.
(see above nocreate parameter)
mustbeposted O módulo edit requer uma solicitação POST.
readapidenied Você precisa da permissão de leitura para usar este módulo.
writeapidenied Você não está autorizado a editar esta wiki através da API.
noapiwrite A edição deste wiki através da API está desabilitada.
badtoken Token de CSRF inválido.
missingparam O parâmetro title, pageid precisa ser definido.
invalidparammix Os parâmetros title, pageid não podem ser usado em conjunto.
invalidtitle Título incorreto "title".
invalid-content-data Dados de conteúdo inválidos
occurs when trying to edit a JSON page with non-conforming data, or while trying to edit a MassMessageListContent page
nosuchpageid Não há página com ID pageid.
pagecannotexist O espaço nominal não permite as páginas atuais.
nosuchrevid Não há revisão com ID undo.
nosuchrevid Não há revisão com ID undoafter.
badmd5 O hash MD5 fornecido estava incorreto.
hookaborted A modificação que você tentou realizar foi abortada por uma extensão.
parseerror Falha na serialização de conteúdo: parseerror
summaryrequired ⧼apierror-summaryrequired⧽
blocked Você foi bloqueado de editar.
ratelimited Você excedeu o limite. Por favor, aguarde algum tempo e tente novamente.
unknownerror Erro desconhecido: "retval".
nosuchsection Não há seção $1.
sectionsnotsupported As seções não são suportadas para o modelo de conteúdo $1.
editnotsupported Editing of this type of page is not supported using the text based edit API.
appendnotsupported Não é possível anexar páginas usando o modelo de conteúdo $1.
redirect-appendonly Você tentou editar usando o modo de redirecionamento, que deve ser usado em conjunto com section=new, prependtext ou appendtext.
edit-invalidredirect Não é possível editar $1 ao seguir redirecionamentos, porque o destino $2 não é válido.
badformat O formato solicitado $1 não é suportado para o modelo de conteúdo $2 usado por $3.
customcssprotected Você não tem permissão para editar esta página CSS, porque ele contém configurações pessoais de outro usuário.
customjsprotected Você não tem permissão para editar esta página de JavaScript, porque ele contém configurações pessoais de outro usuário.
taggingnotallowed You don't have permission to set change tags
badtags A etiqueta "Tag" não pode ser aplicada manualmente.
A seguinte etiqueta não pode ser aplicada manualmente: Tag1, Tag2
tpt-target-page Esta página não pode ser atualizada manualmente.

Esta página é uma tradução da página $1. Sua tradução pode ser atualizada usando [$2 a ferramenta de tradução].
When using Extensão:Translate , editing of a translated subpage is not allowed.

Histórico do parâmetro

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

Ajuda adicional

  • O login não é obrigatoriamente exigido pela API, mas é necessário atribuir corretamente a edição ao seu autor. A edição bem-sucedida de um usuário que não está autenticado (logado) será atribuída ao seu endereço IP.

Os robôs que não estão conectados podem enfrentar restrições à edição e outras solicitações de gravação; veja Manual:Criando um robô de autenticação (login) para mais detalhes. Os usuários que não estiverem conectados sempre receberão o token CSRF vazio, +\

  • The process for requesting a token has changed several times across versions.

Consulte API:Tokens para mais informações.

  • 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 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+.

Ver também

Referências