#!/usr/bin/python3

import requests

S = requests.Session()

URL = "https://test.wikidata.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": "enter_your_username",
    "lgpassword": "enter_your_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 create a data item: "Test 64"
DATA = '{"labels":{"en":{"language":"en","value":"Test 64"}}}'
       
PARAMS_4 = {
    'action': "wbeditentity",
    'new': "item",
    'data': DATA,
    'token': CSRF_TOKEN,
    'format':"json"
}

R = S.post(URL, data=PARAMS_4)

print(R.text)
7ef5cbab8a1a81c2e7963bc2a2bd9ee25d4a1552+\
{"entity":{"labels":{"en":{"language":"en","value":"Test 64"}},"descriptions":{},"aliases":{},"sitelinks":{},"claims":{},"id":"Q210218","type":"item","lastrevid":518548},"success":1}