API:Edit

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

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

POST request to edit a page.

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

Parameters:
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 number. 0 for the top section, new for a new section.

sectiontitle

The title for a new section.

text

Page content.

summary

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

tags

Change tags to apply to the revision.

Values (separate with | or alternative):
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)
basetimestamp

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

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 or do not change watch.

One of the following values: watch, unwatch, preferences, nochange
Default: preferences
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. Overrides text.

appendtext

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

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

undo

Undo this revision. Overrides text, prependtext and appendtext.

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

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
redirect

Automatically resolve redirects.

Type: boolean (details)
contentformat

Content serialization format used for the input text.

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

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

Answer to the CAPTCHA

captchaid

CAPTCHA ID from previous request

Przykład

The sample code in this example is in Python. See API:Edit/Editing with Ajax for examples and responses in Podręcznik: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:Logowanie . 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:Logowanie and API:Tokeny 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.

Odpowiedź

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

Przykładowy kod

edit.py

#!/usr/bin/python3

"""
    edit.py

    MediaWiki Action API Code Samples
    Demo of `Edit` module: POST request to edit a page
    Based on User:Александр Сигачёв, 
    https://www.mediawiki.org/wiki/API:Edit/Editing_with_Python
    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()

print(DATA)

Konflikty edycji

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.

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:

Duże edycje

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.

Możliwe błędy

Kod Info
notitle Parametr title musi być podany.
notext One of the text, appendtext, prependtext and undo parameters must be set
notoken Parametr token musi być podany.
invalidsection The section parameter must be a valid section ID or 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 Artykuł, który próbowałeś utworzyć, już został utworzony.
noimageredirect-anon Anonimowi użytkownicy nie mogą tworzyć przekierowań plików.
noimageredirect Nie masz uprawnień do tworzenia przekierowań plików.
spamdetected Your edit was refused because it contained a spam fragment: Wikitext.
filtered The filter callback function refused your edit
contenttoobig ⧼Apieror-contenttoobig⧽
noedit-anon Niezarejestrowani użytkownicy nie mogą edytować stron.
noedit Nie masz uprawnień do edytowania stron.
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 Edit conflict detected
revwrongpage rrevid nie jest wersją strony pagename.
Thrown if an invalid revid is given for undo or undoafter
undofailure Undo failed due to conflicting intermediate edits
missingtitle Wybrana przez ciebie strona nie istnieje.
(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. Make sure the $wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file.
badtoken Nieprawidłowy token CSRF.
missingparam Parametr title, pageid musi być podany.
invalidparammix Parametry title, pageid nie mogą być używane razem.
invalidtitle Zły tytuł „title”.
nosuchpageid Nie ma strony z identyfikatorem pageid.
pagecannotexist Namespace doesn't allow actual pages.
nosuchrevid Nie ma wersji z identyfikatorem undo.
nosuchrevid Nie ma wersji z identyfikatorem undoafter.
undofailure Undo failed due to conflicting intermediate edits
badmd5 The supplied MD5 hash was incorrect.
hookaborted Zmiana, którą próbowałeś wykonać została przerwana przez hak rozszerzenia.
parseerror Failed to parse the given text.
summaryrequired Summary required
blocked Została Ci zablokowana możliwość edycji.
ratelimited You've exceeded your rate limit. Please wait some time and try again.
unknownerror Nieznany błąd: „retval”.
nosuchsection Nie ma sekcji $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.
badformat The requested format $1 is not supported for content model $2 used by $3.
customcssprotected Nie jesteś uprawniony do edytowania tej strony CSS, ponieważ zawiera ona ustawienia osobiste innego użytkownika.
customjsprotected Nie jesteś uprawniony do edytowania tej strony JavaScript, ponieważ zawiera ona ustawienia osobiste innego użytkownika.
taggingnotallowed You don't have permission to set change tags
tpt-target-page Ta strona nie może zostać zaktualizowana ręcznie.

Jest ona tłumaczeniem strony $1, a tłumaczenie może zostać zmienione za pomocą [$2 narzędzia tłumacza].
When using Extension:Translate, editing of a translated subpage is not allowed.


Parameter history

  • 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

Additional notes

  • 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:Tokeny for more information.
  • 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+.

Zobacz też

Przypisy