29

I have the following site in SharePoint 2013 in my local VM:

http://win-5a8pp4v402g/sharepoint_test/site_1/

When I access this from the browser, it prompts me for the username and password and then works fine. However I am trying to do the same using the REST API in Python. I am using the requests library, and this is what I have done:

import requests
from requests.auth import HTTPBasicAuth


USERNAME = "Administrator"

PASSWORD = "password"

response = requests.get("http://win-5a8pp4v402g/sharepoint_test/site_1/", auth=HTTPBasicAuth(USERNAME, PASSWORD))

print response.status_code

However I get a 401. I dont understand. What am I missing?

Note: I followed this article http://tech.bool.se/using-python-to-request-data-from-sharepoint-via-rest/

Indradhanush Gupta
  • 4,067
  • 10
  • 44
  • 60

4 Answers4

43

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: http://docs.python-requests.org/en/latest/user/authentication/

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("http://sharepoint-site.com", auth=HttpNtlmAuth('DOMAIN\\USERNAME','PASSWORD'))
TomL
  • 2,724
  • 1
  • 17
  • 7
  • It works like a charm. HttpNtlmAuth(uid, pwd) is what fixed the issue . Its for intranet sharepoint where i needed this code. Thanks for sharing. – Doogle Jun 13 '18 at 08:28
  • 6
    I am getting from intranet and internet. Any idea how to resolve?, thx – user3867743 Mar 02 '20 at 20:36
  • Just in case someone has NTLM locked down in his/her company: There is also an option to use the requests_negotiate_sspi package. See [this link](https://qurios-it.de/2020/10/16/connecting-to-sharepoint-using-python/) for an overview of the options. – Stephan Oct 16 '20 at 10:47
4

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 = "https://sharepoint.mycompany.com"
headers = {'accept': "application/json;odata=verbose","content-type": "application/json;odata=verbose"}
##"DOMAIN\username",password 
auth = HttpNtlmAuth("MYCOMPANY"+"\\"+"UserName",'Password')


def getToken():
    contextinfo_api = root_url+"/_api/contextinfo"
    response = requests.post(contextinfo_api, 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,
            'Language':1033,
            'WebTemplate':'STS#0',
            'UseUniquePermissions':True}
        }
    response = requests.post(create_api, auth=auth,headers=headers,data=json.dumps(payload))
    return json.loads(response.text)

headers['X-RequestDigest']=getToken()
print createSite("Human Resources","hr","Sample Description")
  • 1
    I am getting on headers['X-RequestDigest']=getToken() as follows:KeyError: 'd', testing it within the company's network – user3867743 Mar 02 '20 at 20:38
1

You can also use Office365-REST-Python-Client ("Office 365 & Microsoft Graph Library for Python") or sharepoint ("Module and command-line utility to get data out of SharePoint")

ndemou
  • 4,691
  • 2
  • 30
  • 33
  • I found this option today. Question: is there any security risk to entering credentials through a python library? – Branden Keck Oct 09 '20 at 11:24
  • 1
    Same as with any other open source library. If you audit the code and handle the password with diligence you are safe enough. – ndemou Oct 09 '20 at 15:12
-1

A 401 response is an authentication error...

That leaves one of your three variables as incorrect: url, user, pass. Requests Authentication Docs

Your url looks incomplete.

Justin Poehnelt
  • 2,992
  • 1
  • 19
  • 23
  • Yes I know its an access denied error. Point is I have verified that the url, username and password are correct. – Indradhanush Gupta Jan 06 '14 at 08:46
  • Thats allright. Its a sharepoint site. I have added that entry in /etc/hosts file to point to the IP of the local VM. Anyways, for the sake of clarity, I have updated the url. – Indradhanush Gupta Jan 06 '14 at 08:55