API:Edit/Editing with Python

From MediaWiki.org
Jump to: navigation, search

Edit example in Python, regarding the API:Edit article (based on User:Sebelino7/Login with Python)

Tested with MediaWiki 1.29.0-wmf.1 and Python 2.7.8 on 7 November 2016

# -*- coding: utf-8 -*-
import requests

username = 'USERNAME'
password = 'PASSWORD' # see https://www.mediawiki.org/wiki/Manual:Bot_passwords
api_url = 'https://test.wikipedia.org/w/api.php'
summary = 'bot hello'
message = 'Hello Wikipedia. I am alive!'
page = 'Sandbox'

session = requests.Session()

# get login token
r1 = session.get(api_url, params={
    'format': 'json',
    'action': 'query',
    'meta': 'tokens',
    'type': 'login',
})
r1.raise_for_status()

# log in
r2 = session.post(api_url, data={
    'format': 'json',
    'action': 'login',
    'lgname': username,
    'lgpassword': password,
    'lgtoken': r1.json()['query']['tokens']['logintoken'],
})
if r2.json()['login']['result'] != 'Success':
    raise RuntimeError(r2.json()['login']['reason'])

# get edit token
r3 = session.get(api_url, params={
    'format': 'json',
    'action': 'query',
    'meta': 'tokens',
})

# save the edit
r4 = session.post(api_url, data={
    'format': 'json',
    'action': 'edit',
    'assert': 'user',
    'appendtext': message,
    'summary': summary,
    'title': page,
    'token': r3.json()['query']['tokens']['csrftoken'],
})

print (r4.text)