Search code examples
pythonsharepointkeyerror

Receive keyerror when attempting to authorize myself into sharepoint site


I am trying to connect to a SharePoint Online site using Python. I have found the Office365-REST-Python-Client on GitHub and have been using that as a guide. I have used "pip install Office365-REST-Python-Client" and it installed without any issue. In the examples folder, I am following along with the file named "listitems_operations_alt.py". If I paste the code into my python file and do not alter it at all, I receive an error saying, "NameError: name 'urlparse' is not defined". If I attempt to alter the url to match my SharePoint Online site's url, I receive an error "KeyError: 'mysite.sharepoint.com'". I am not exactly sure what is causing this issue. below is my code.

from examples.settings import settings
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_request import ClientRequest


def read_list_items(web_url, ctx_auth, list_title):
    """Read list items example"""
    request = ClientRequest(web_url, ctx_auth)
    request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items".format(web_url, list_title)  # Web resource endpoint

    print("Retrieving list items from List {0}".format(list_title))
    data = request.execute_request_direct(request_url=request_url)
    for item in data['d']['results']:
        print("Item title: {0}".format(item["Title"]))


def create_list_item(web_url, ctx_auth, list_title):
    """Create list item example"""
    request = ClientRequest(web_url, ctx_auth)
    request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items".format(web_url, list_title)  # Web resource endpoint

    print("Creating list item...")
    item_payload = {'__metadata': {'type': 'SP.Data.TasksListItem'}, 'Title': 'New Task'}
    data = request.execute_request_direct(request_url=request_url, data=item_payload)
    print("Task {0} has been successfully [created]".format(data['d']['Title']))
    return data['d']


def update_list_item(web_url, ctx_auth, list_title, item_id):
    """Update list item example"""
    request = ClientRequest(web_url, ctx_auth)
    request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items({2})".format(web_url, list_title, item_id)
    print("Updating list item...")
    item_payload = {'__metadata': {'type': 'SP.Data.TasksListItem'}, 'Title': 'New Task (updated)'}
    headers = {
        'IF-MATCH': '*',
        'X-HTTP-Method': 'MERGE'
    }
    request.execute_request_direct(request_url=request_url, headers=headers, data=item_payload)
    print("Task has been successfully [updated]")


def delete_list_item(web_url, ctx_auth, list_title, item_id):
    """Delete list item example"""
    request = ClientRequest(web_url, ctx_auth)
    request_url = "{0}/_api/web/lists/getbyTitle('{1}')/items({2})".format(web_url, list_title, item_id)
    print("Deleting list item...")
    headers = {
        'IF-MATCH': '*',
        'X-HTTP-Method': 'DELETE'
    }
    request.execute_request_direct(request_url=request_url, headers=headers)
    print("Task has been successfully [deleted]")


if __name__ == '__main__':
    context_auth = 
AuthenticationContext(url=settings['mysite.sharepoint.com'])
    if context_auth.acquire_token_for_user(username=settings['username'], 
password=settings['password']):

        read_list_items(settings['url'], context_auth, "Tasks")
        task_item = create_list_item(settings['url'], context_auth, "Tasks")
        update_list_item(settings['url'], context_auth, "Tasks", task_item['Id'])
        delete_list_item(settings['url'], context_auth, "Tasks", task_item['Id'])

    else:
        print(context_auth.get_last_error())

Solution

  • If you are installing Office365-REST-Python-Client package from python package index then unfortunately its version (2.0.0) is already outdated, in particular it does not support Python 3 runtime, that's probably the reason why the provided error occurs.

    Try to install the latest version (2.1.1) from GitHub instead, like this:

    pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git 
    

    enter image description here

    Example

    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
    from office365.sharepoint.client_context import ClientContext
    
    settings = {
        'url': 'https://contoso.sharepoint.com/',
        'user_credentials': {
            'username': '',
            'password': ''
        }
    }
    
    
    def read_list_items(context, list_title):
        """Read list items example"""
        request = ClientRequest(context)
        options = RequestOptions("{0}web/lists/getbyTitle('{1}')/items".format(context.service_root_url, list_title))
        options.set_header('Accept', 'application/json; odata=nometadata')
    
        print("Retrieving list items from List {0}".format(list_title))
        response = request.execute_request_direct(options)
        data = json.loads(response.content)
        for item in data['value']:
            print("Item title: {0}".format(item["Title"]))
    
    
    if __name__ == '__main__':
        ctx_auth = AuthenticationContext(url=settings['url'])
        if ctx_auth.acquire_token_for_user(username=settings['user_credentials']['username'],
                                           password=settings['user_credentials']['password']):
            target_list_title = "Tasks"
            ctx = ClientContext(settings['url'], ctx_auth)  # Initialize client context
            read_list_items(ctx, target_list_title)
        else:
            print(ctx_auth.get_last_error())