tivoo
tivoo

Reputation: 125

Load files from SharePoint in Python

So I am trying to load files located in (sub)directories in Python using this bit of code:

import json

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_request import ClientRequest
from office365.runtime.utilities.request_options import RequestOptions

ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
  request = ClientRequest(ctx_auth)
  options = RequestOptions("{0}/_api/web/".format(url))
  options.set_header('Accept', 'application/json')
  options.set_header('Content-Type', 'application/json')
  data = request.execute_request_direct(options)
  s = json.loads(data.content)
  web_title = s['Title']
  print("Web title: " + web_title)
else:
  print(ctx_auth.get_last_error())

But I am getting the following error:

Cannot get binary security token for from https://login.microsoftonline.com/extSTS.srf An error occurred while retrieving auth cookies from https:/DOMAIN.website/siteDocuments/Document/example/

Now the Microsoft link says the endpoint only accepts POST requests. Received a GET request.

Is there any workaround for this? Thanks.

Upvotes: 6

Views: 18115

Answers (1)

Baker_Kong
Baker_Kong

Reputation: 1889

I tested this code on my SP online. Please modify your code as below:

import json

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_request import ClientRequest
from office365.runtime.http.request_options import RequestOptions

tenant_url= "https://{tenant}.sharepoint.com"
ctx_auth = AuthenticationContext(tenant_url)

site_url="https://{tenant}.sharepoint.com/sites/{yoursite}"

if ctx_auth.acquire_token_for_user("username","password"):
  request = ClientRequest(ctx_auth)
  options = RequestOptions("{0}/_api/web/".format(site_url))
  options.set_header('Accept', 'application/json')
  options.set_header('Content-Type', 'application/json')
  data = request.execute_request_direct(options)
  s = json.loads(data.content)
  web_title = s['Title']
  print("Web title: " + web_title)
else:
  print(ctx_auth.get_last_error())

Result: enter image description here

Upvotes: 4

Related Questions