Insert into SharePoint List using Python

To get past SharePoint authentication, we need to get ClientID and access key,
Open this link to register new App
https://<site>/_layouts/15/AppRegNew.aspx

In order to access this registration page, you may need to have an access collection administrator and above.

Click on generate for both Client id and client secret

Next step is to grant permission to the newly created principal (App)
In order to access the page, go to the link
https://<site>/_layouts/15/AppInv.aspx

Make a note of the client id that was generated in step 1, Paste the client id and click on “Lookup”

<AppPermissionRequests AllowAppOnlyPolicy="true">
  <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>

Paste the above XML in Permission request xml

Click on “Trust it” , now this should give access to the sharepoint

create a new list library “Testing” with two columns “Title” and “Status” in sharepoint
install office365 client library
pip install Office365-REST-Python-Client

Below code will insert values into Title and Status field in Testing list library

/

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

app_settings = {
        'url': "https://<sharepoint link>/",
        'client_id': "489e83b7-d47b-4d08-abce-02be0fa849c2",
        'client_secret': "jNSKgOJCPwKMnt+GUIZqOPezaD5u7S0x/fUtjtX0Mys=",
    }
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)

list = ctx.web.lists.get_by_title("Testing")
list.add_item({'Title': "Testing", 'status': "Pending"})
ctx.execute_query()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.