user3249433
user3249433

Reputation: 601

download sharepoint 365 document using python

I am trying to automate the download of sharepoint office 365 files using Python. I found the following client https://github.com/vgrem/Office365-REST-Python-Client

However my requirement is to use a simple client that uses a clientid and secret to grab a acesses token and then download the file.

If you understand OAuth2 then this flow is called client credential grant. But when i go through the Python Client in the examples section i see

settings.py
settings = {
    'url': 'https://mediadev20.sharepoint.com/sites/contoso',
    'username': '[email protected]',
    'password': 'P@ssw0rd'
}

app_settings = {
    'url': 'https://mediadev20.sharepoint.com/sites/contoso',
    'client_id': '99cbd1a9-ec8d-4e89-96c3-699993089d65',
    'client_secret': 'VMdT8mOurDhsvG8yDnP3yFg',
    'redirect_url': 'https://github.com/vgrem/Office365-REST-Python-Client/'
}

My problem is i do not know what to with the redirect_url as mine is a standalone client and there is no redirect_url as such.

Does anyone have a sample code or a pointer on how i can use that library without using redirect_url ?

Upvotes: 1

Views: 7010

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59328

For that scenario you could consider to grant access via SharePoint App-Only flow. In the latest version of library the support for SharePoint App-Only access has been introduced:

AuthenticationContext.acquire_token_for_app(client_id,client_secret)

Follow this article on how to grant access using SharePoint App-Only, below i will summarize the main points:

  • First of all, you need to setup your app-only principal
  • Next step is granting permissions to the newly created principal
  • Once the principal is created and consented you can use the principal's id and secret to request an access as demonstrated below:

Example:

from office365.runtime.auth.authentication_context import AuthenticationContext

app_settings = {
    'url': 'https://contoso.sharepoint.com/',
    'client_id': '8efc226b-ba3b-4def-a195-4acdb8d20ca9',
    'client_secret': '',
}

context_auth = AuthenticationContext(url=app_settings['url'])
context_auth.acquire_token_for_app(client_id=app_settings['client_id'], client_secret=app_settings['client_secret'])

ctx = ClientContext(app_settings['url'], context_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web site title: {0}".format(web.properties['Title']))

Upvotes: 2

Related Questions