Sharepoint API with Python

Navid 0 Reputation points
2024-12-18T17:20:28.86+00:00

Hello everyone, I have been struggling for weeks to connect to sharepoint and automate some of my ETL tasks using python.

So basically I have followed the following instructions:

Step 1: Register an Application in Azure Active Directory

  1. Log in to Azure Portal:
    1. Navigate to App Registrations:
      • In the Azure AD menu, select "App registrations".
        • Click "New registration".
        1. Fill in the App Registration Details:
          • Name: Enter a name for your application (e.g., "SharePointETLApp").
            • Supported Account Types: Choose "Accounts in this organizational directory only" if you're targeting your organization.
              • Redirect URI: You can leave this blank for now (it's used for interactive logins, not for service-to-service apps).
                • Click "Register".
                1. Obtain the Client ID:
                  • Once registered, go to the app's overview page.
                    • Copy the Application (client) ID. This is your SHAREPOINT_CLIENT_ID.

Step 2: Create a Client Secret

  1. In your registered application, navigate to the "Certificates & Secrets" tab under Manage on the left bar.
  2. Under Client Secrets, click "New client secret".
  3. Provide a description (e.g., "SharePointAccessSecret").
  4. Set an expiration period (e.g., 6 months, 1 year, or custom).
  5. Click "Add".
  6. Copy the generated secret value immediately. This is your SHAREPOINT_CLIENT_SECRET. (You won’t be able to see it again later.)

Step 3: Grant Permissions to the App

  1. Go to the "API Permissions" tab in your application.
  2. Click "Add a permission".
  3. Select "Microsoft Graph" and then "Delegated permissions" or "Application permissions" based on your needs:
    • For accessing SharePoint files, add:
           - Sites.FullControl.All
           
      

After all, I went to this link on sharepoint https://[tenant].sharepoint.com/sites/tasks/_layouts/15/AppRegNew.aspx
And registered my app and clicked on Trust button

Later I went to this address /_layouts/15/AppPrincipals.aspx to check if the app is there, and I cannot find my app that I registered in the previous step

this is my python code:

from office365.runtime.auth.client_credential import ClientCredential

from office365.sharepoint.client_context import ClientContext

site_url = """https://[tenant].sharepoint.com/sites/tasks/"""

client_id = """client_id"""

client_secret = """client_secret"""

def test_connection(site_url, client_id, client_secret):

    credentials = ClientCredential(client_id, client_secret)

    ctx = ClientContext(site_url).with_credentials(credentials)

    try:

        web = ctx.web

        ctx.load(web)

        ctx.execute_query()

        print(f"Successfully connected to SharePoint site: {web.properties['Title']}")

    except Exception as e:

        print(f"An error occurred: {e}")

test_connection(site_url, client_id, client_secret)

And here is the output:
An error occurred: (None, None, '401 Client Error: Unauthorized for url: https://[tenant].sharepoint.com/sites/tasks/_api/Web')

I checked so many sources but I am getting really confused.
I would appreciate if anyone that has exprienced this, help me figure out how I can solve my question and finally be able to access sharepoint using python

SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
3,152 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Emily Du-MSFT 48,566 Reputation points Microsoft Vendor
    2024-12-19T02:23:41.5566667+00:00

    After registering an app in the SharePoint site collection, you must need to give permission to the app.

    Go to https://tenant.sharepoint.com/sites/sitecollection/_layouts/15/appinv.aspx, for the "App Id", try entering in the "Client ID" that generated earlier, then press the "Lookup" button.

    While for the “Permission Request XML”, type the following. Make you replace your Scope.

    <AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="https://tenant.sharepoint.com/sites/sitecollection" Right="FullControl" />
    </AppPermissionRequests>
    

    1

    Reference:

    https://www.billyperalta.com/Accessing%20SharePoint%20REST%20API%20using%20Postman/#registering-an-app-in-sharepoint

    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.