How to access a sharepoint site via the REST API in Python?

Here is an examples of SharePoint 2016 REST API call from Python to create a site.

import requests,json,urllib
from requests_ntlm import HttpNtlmAuth

root_url = ""
headers = {'accept': "application/json;odata=verbose","content-type": "application/json;odata=verbose"}
auth = HttpNtlmAuth("MYCOMPANY"+"\\"+"UserName",'Password')

def getToken():
    contextinfo_api = root_url+"/_api/contextinfo"
    response =, auth=auth,headers=headers)
    response =  json.loads(response.text)
    digest_value = response['d']['GetContextWebInformation']['FormDigestValue']
    return digest_value

def createSite(title,url,desc):
    create_api = root_url+"/_api/web/webinfos/add"
    payload = {'parameters': {
            '__metadata':  {'type': 'SP.WebInfoCreationInformation' },
            'Url': url,
            'Title': title,
            'Description': desc,
    response =, auth=auth,headers=headers,data=json.dumps(payload))
    return json.loads(response.text)

print createSite("Human Resources","hr","Sample Description")

It's possible that your SharePoint site uses a different authentication scheme. You can check this by inspecting the network traffic in Firebug or the Chrome Developer Tools.

Luckily, the requests library supports many authentication options:

Fore example, one of the networks I needed to access uses NTLM authentication. After installing the requests-ntml plugin, I was able to access the site using code similar to this:

import requests
from requests_ntlm import HttpNtlmAuth

requests.get("", auth=HttpNtlmAuth('DOMAIN\\USERNAME','PASSWORD'))