#!/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"]

ID = "Q210218"
PROPERTY = "P7"

# Step 4: Send a post request to create a new claim on the property P7 for the item Q210218
DATA = '{"claims":[{"mainsnak":{"snaktype": "value", "property": "P7", "datavalue": { "value": {"entity-type": "item","numeric-id": 210218, "id": "Q210218"}, "type": "wikibase-entityid"}}, "type": "statement", "rank": "normal"}]}'

PARAMS_4 = {
    'action': "wbeditentity",
    'id': ID,
    'data': DATA,
    'token': CSRF_TOKEN,
    'format':"json"
}

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

print(R.text)
{"entity":{"labels":{"en":{"language":"en","value":"Test 64"}},"descriptions":{},"aliases":{},"sitelinks":{},"claims":{"P7":[{"mainsnak":{"snaktype":"value","property":"P7","hash":"bea882d7896b3e881c62d41a95c10592f6a6aac8","datavalue":{"value":{"entity-type":"item","numeric-id":210218,"id":"Q210218"},"type":"wikibase-entityid"},"datatype":"wikibase-item"},"type":"statement","id":"Q210218$B623AFA9-4365-49E5-85AE-0386165D3E49","rank":"normal"}]},"id":"Q210218","type":"item","lastrevid":518551},"success":1}