Tag: MS Graph

  • How To Download a SharePoint Library Using Graph API (PowerShell)

    SharePoint is a powerful platform for managing and collaborating on documents, but downloading files from SharePoint libraries can be a tricky, especially when it comes to deal with large files or a large amount of documents. In this post, I want to show you a straightforward guide to download a SharePoint Library using PowerShell with Microsoft’s Graph API for SharePoint administrators, developers or system integrators. This tutorial will help you streamline your automation in terms of downloading SharePoint libraries. At the end, you’ll find a ready to use PowerShell script, which you can use to download the SharePoint Library using Graph API.

    If you want to download a SharePoint library using Graph API, there are certain prerequisites you must fulfil. To successfully download files from SharePoint using Graph API, you need to ensure the following:

    What do I need to download files to SharePoint using Graph API?

    • You have the sites.selected permission for an Azure Enterprise Application. Your global administrator in your organization can consent this permission.
    • You have installed the PNP PowerShell module to allow the Enterprise Application permission to download files from the specific SharePoint Site. Without this module, the Enterprise Application will not be able to access and download the files. Learn here how you can install the PNP PowerShell module:
      Connect to SharePoint with PowerShell | SharePoint Online (workplace-automation.com/)

    By fulfilling these prerequisites, you can easily download SharePoint libraries using Graph API and streamline your document management process.

    How to create the Enterprise Application to Download a SharePoint Library using Graph?

    1. Go to the Azure Active Directory Portal to create an App Registration with Sites.Selected permissions. This allows the Enterprise Application to access and download files from SharePoint.
    2. Create a credential object for the App registration.
    3. Once you have created the credentials for the App Registration, make sure to note down the credentials for future use. These credentials will be required when you are running the PowerShell script to download a SharePoint Library using Graph.

    By following these simple steps, you can create an Enterprise Application with the necessary permissions to download files from SharePoint using Graph API. You will get to know in the upcoming passage how to create the Enterprise Application step-by-step.

    Browse to Azure Active Directory Portal

    Open https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade in your browser.

    If you have the global admin rights, I recommend authenticating with that account, so that you can directly grant your enterprise application the permission. Otherwise, you need to reauthenticate or ask your administrator to grant your enterprise application the permissions.

    Create an App Registration with Sites.Selected permissions

    Browse to the App Registration blade in Azure Active Directory Portal.

    Screenshot of the App registration Azure Active Directory Tenant overview

    Click on “New registration” to create a new App Registration.

    Screenshot of new enterprise app registration

    Define a meaningful name for the App that follows your organization’s standards, so that different administrators can easily recognize the purpose of the App. In this case I am using the name SP_Sites.Selected_Retail name, so that Azure Active directory administrators can recognize that the App Registration will have the permission Sites.Selected for the SharePoint Site Retail

    Browse to the “API Permissions” to grant your App Registraion the permission to download the SharePoint Library using Graph API.

    Screenshot of API Permissions link

    Click on “Add a permission”

    Screenshot of API Permissions overview to add a permission

    As we want to go with Microsoft Graph, please choose “Microsoft Graph”.

    Screenshot of the selection for APIs

    To download a SharePoint library using Graph API, it’s crucial to choose the right permission level. If you want your application to run in the background without requiring user authentication, you’ll need to select the Application permission option. In this tutorial on how to download a SharePoint library using Graph API, we’ll focus on the application permission method to automate the process of downloading files from SharePoint.

    Screenshot of API permission types

    Now add the sites.selected permission, which allows you to access contents of a single SharePoint site.

    Screenshot of Microsoft Graph Permissions for SharePoint Sites

    To grant admin consent for your tenant, you must be signed in with a user account that has global administrator privileges. However, if you don’t have these privileges ask your administrator with the global administrator role to consent permissions for the App Registration.

    Screenshot of granting of admin consent for current tenant

    Create a secret for the App Registration

    Now as you have configured the App permissions, you have to ensure, that you can authenticate with your App Registration. To configure the authentication, click on “Certificates & secrets”.

    Screenshot of certificates & secrets of App Registrations

    Now you can either upload certificates, create client secrets or create federated credentials. In this tutorial I will show you how to work with client secrets.

    Screenshot of Selection for App Registration Authentication

    Now you need to define a credential name. I choose the client and the IP Address to recognize, which Server/ Application will use the client secret.

    Screenshot of Add a client secret

    As you have added a client secret, make sure that you store the value for the secret as you are only able to see it, when you create it.

    Screenshot of exposed client secret value

    How to grant the App Registration Permissions for a SharePoint Site?

    To grant permission to your app registration, it’s essential to ensure that the PNP Module is installed on your client and that you have permission to use it. If you haven’t already installed the PNP Module, check out the documentation: Connect to SharePoint with PowerShell | SharePoint Online (workplace-automation.com/)

    Once you have confirmed that both conditions are met, you can use the following code to grant your app registration the necessary permissions to read from the site. You can find your app ID on the overview page of your app registration.

    Take the App ID from the overview page of your App registration and run the code below.

    Screenshot of App ID
    $AppID = "333d169e-7f2d-417c-b349-8498b2248802"
    $AppRegistrationName = "SP_Sites.Selected_Retail"
    $SiteURL = "https://m365x69801090.sharepoint.com/sites/Retail"
    
    Import-Module PnP.PowerShell
    
    $DisplayNameofSitePermission = "Enterprise Application $AppRegistrationName"
    
    
    Connect-PnPOnline -Url $SiteURL -Interactive
    Grant-PnPAzureADAppSitePermission -AppId $AppID -DisplayName $DisplayNameofSitePermission -Site $SiteURL -Permissions Read

    Now login with your account.

    Screenshot of interactive authentication prompt

    This is how it looks like, when the permission was granted successfully for the App Registration.

    Screenshot of granted site permission

    How to Download Files from SharePoint using Graph API?

    Now that we’ve created an app registration and granted it permission to write to a selected site, we can use it to download a SharePoint Library using Graph API. In this example, we’ll download the SharePoint Library Documents from the Retail SharePoint site. Before running the code, make sure you have adjusted the parameters and have the client secret ready, which we created in the previous steps.

    You can get the SiteID by browsing to the siteID page

    <siteurl>/_api/site/id

    For my example:

    https://m365x69801090.sharepoint.com/sites/Retail/_api/site/id

    When you run the code, you’ll be prompted to enter the client secret for your app registration.

    Screenshot of SharePoint Site ID

    Once you have replaced the parameters with your actual values, you can download aSharePoint Library with Graph using PowerShell. You will get an authentication prompt, where you have to enter the client secret for the App Registration.

    Screenshot of authentication promt for app registration

    # Script to download a SharePoint Library using Graph
    # Author: Serkar Aydin - Serkar@workplace-automation.com
    # Accept input parameters
    Param (
        $Tenant = "m365x69801090",
        $AppID = "333d169e-7f2d-417c-b349-8498b2248802",
        $SiteID = "74667e94-9fcf-41ab-8e2f-0dfaf0294de8",
        $LibraryURL = "https://m365x69801090.sharepoint.com/sites/Retail/Shared%20Documents",
        $Path = "C:\Users\Serkar\Desktop\Retail"
    )
    
    Function DownloadDriveItem {
    
        param(
            $DriveItem,
            $URL,
            $Header,
            $Path
            
        )
        
        #if there is no downloadurl, it is a folder
        If (!$DriveItem. '@microsoft.graph.downloadUrl') {
        
            Write-Output "Downloading the folder $($DriveItem.weburl)"
        
            #Create a folder for the SharePoint folder
            $FolderPath = "$Path\$($DriveItem.name)"
            New-Item -ItemType Directory -Path $FolderPath | Out-Null
    
            $Url  = "https://graph.microsoft.com/v1.0/drives/$DriveID/items/$($DriveItem.ID)/children"
            $Response =  Invoke-RestMethod -Uri $Url -Headers $Header -Method Get -ContentType 'multipart/form-data' 
    
            $Response.value | ForEach-Object {
    
                DownloadDriveItem -DriveItem $_ -URL $Url -Header $Header -Path $FolderPath
    
            }
    
        }
    
        #Else it is a file
        Else{
        
            Write-Output "Downloading the file $($DriveItem.weburl)"
            Invoke-WebRequest -Uri $DriveItem.'@microsoft.graph.downloadUrl' -OutFile "$Path\$($DriveItem.name)"
        }
    }
    
    
    # Prompt for application credentials
    $AppCredential = Get-Credential($AppID)
    
    #region authorize
    
    # Set the scope for the authorization request
    $Scope = "https://graph.microsoft.com/.default"
    
    # Build the body of the authorization request
    $Body = @{
        client_id = $AppCredential.UserName
        client_secret = $AppCredential.GetNetworkCredential().password
        scope = $Scope
        grant_type = 'client_credentials'
    }
    
    # Build the URL for the authorization request
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    
    # Send the authorization request and retrieve the access token
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
    $Access_token = $AuthorizationRequest.Access_token
    
    # Build the header for API requests
    $Header = @{
        Authorization = $AuthorizationRequest.access_token
        "Content-Type"= "application/json"
    }
    
    #endregion
    
    #region get drives
    
    # Build the URL to retrieve the list of drives in the SharePoint site
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives"
    
    # Convert the body of the authorization request to JSON and send the API request
    $BodyJSON = $Body | ConvertTo-Json -Compress
    $Result = Invoke-RestMethod -Uri $GraphUrl -Method 'GET' -Headers $Header -ContentType "application/json"
    
    # Find the ID of the specified SharePoint library
    $DriveID = $Result.value| Where-Object {$_.webURL -eq $LibraryURL } | Select-Object id -ExpandProperty id
    
    # If the SharePoint library cannot be found, throw an error
    If ($DriveID -eq $null){
        Throw "SharePoint Library under $LibraryURL could not be found."
    }
    
    #endregion
    
    #region create folder. If there is already one, replace it with the new folder
    
    Try {
    
        New-Item -ItemType Directory -Path $Path -ErrorAction Stop | Out-Null
    }
    Catch {
    
            Remove-Item $Path -Force -Recurse
            New-Item -ItemType Directory -Path $Path -Force | Out-Null
    }
    #endregion
    
    #region download library
    
    $Url  = "https://graph.microsoft.com/v1.0/drives/$DriveID/root/children"
    $Response =  Invoke-RestMethod -Uri $Url -Headers $Header -Method Get -ContentType 'multipart/form-data' 
    
    $Response.value | ForEach-Object {
    
        DownloadDriveItem -DriveItem $_ -URL $Url -Header $Header -Path $Path
    
    }
    
    #endregion
    Screenshot of the process "Download a SharePoint Library using Graph"

    As you can see, I was able to download a SharePoint Library using Graph API. All folders and subfolders are created on my local C drive. Result of Download a SharePoint Library using Graph 1

    Result of Download a SharePoint Library using Graph 1
    Result of Download a SharePoint Library using Graph File share 1
    Result of Download a SharePoint Library using Graph 2
    Result of Download a SharePoint Library using Graph File share 2
    Result of Download a SharePoint Library using Graph 3
    Result of Download a SharePoint Library using Graph File share 3

    Further Reference

    You might want to download single files from SharePoint with Graph API? Check this out:
    How to download files from SharePoint using Graph API (PowerShell) (workplace-automation.com/)

    Learn how to access SharePoint via Graph in PowerShell: Access SharePoint via Graph API in PowerShell

    Learn how to upload files to SharePoint using Graph (PowerShell):
    How to Upload Files to SharePoint using Graph API PowerShell (workplace-automation.com/)

  • How to download files from SharePoint using Graph API (PowerShell)

    How to download files from SharePoint using Graph API (PowerShell)

    Downloading files from SharePoint is a common use case, when we are integrating 3rd party systems with SharePoint. In my previous articles, I have been explaining how you can upload files to SharePoint using PNP module. In this article, I want to show you how you can achieve download files from SharePoint using Graph API.

    In the beginning, we will create an Entra ID Enterprise Application in Entra ID, grant the created Enterprise Application the permission to interact with selected sites. At the end, I will share a PowerShell script to download files from the SharePoint using Graph API.

    What do I need to download files to SharePoint using Graph API?

    To downlaod a file to SharePoint using Graph API, you need the following prerequisites fulfilled:

    Your Sites.Selected App registration shall have following permission (at least):

    Screenshot of app registration with sites selected permissions

    How to Download Files from SharePoint using Graph API?

    As we have created an app registration and gave it the permission to write to a selected site, we can use to download files from SharePoint using Graph API. In my example, I want to download an Excel file from the SharePoint Library Shared Documents. Make sure, that you have adjusted the parameters and have the client secret handy, which we have created in the previous steps.

    Before you run the code, change the value of there parameters:

    $Tenant = “m365x323732” -> Name of the tenant. You can fetch it from the URL of your SharePoint: https://m365x16735261.sharepoint.com

    $AppID = “e0b8aefa-cb52-4bda-93a0-7d87120bcdbb” -> App ID, which you previously created in Entra ID

    $SiteID = “e35cee33-6d10-4e2c-a83b-496a26062ad3” -> ID of the Site, where you want to download the file from. In my example it would be https://m365x323732.sharepoint.com/sites/SalesAndMarketing/_api/site/id

    $LibraryURL = “https://m365x323732.sharepoint.com/sites/SalesAndMarketing/Shared%20Documents” -> URL to the SharePoint Library, where the file is located, which you want to download.

    $Path = “C:\Users\Serkar\Desktop\DG-2000 Product Specification.docx” – Path to where the file should be downloaded to

    $FileName = “DG-2000 Product Specification.docx” -> Name of the file

    When you run the code, you will be asked to provide the client secret for your app registration.

    Screenshot of credential prompt
    Param (
        $Tenant = "m365x323732",
        $AppID = "e0b8aefa-cb52-4bda-93a0-7d87120bcdbb",
        $SiteID = "e35cee33-6d10-4e2c-a83b-496a26062ad3",
        $LibraryURL = "https://m365x323732.sharepoint.com/sites/SalesAndMarketing/Shared%20Documents",
        $Path = "C:\Users\Serkar\Desktop\DG-2000 Product Specification.docx",
        $FileName = "DG-2000 Product Specification.docx"
    )
    
    $AppCredential = Get-Credential($AppID)
    
    #region authorize
    $Scope = "https://graph.microsoft.com/.default"
    
    $Body = @{
        client_id = $AppCredential.UserName
        client_secret = $AppCredential.GetNetworkCredential().password
        scope = $Scope
        grant_type = 'client_credentials'
    }
    
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
    $Access_token = $AuthorizationRequest.Access_token
    
    $Header = @{
        Authorization = $AuthorizationRequest.access_token
        "Content-Type"= "application/json"
    }
    #endregion
    
    #region get drives
    
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives"
    
    $BodyJSON = $Body | ConvertTo-Json -Compress
    $Result = Invoke-RestMethod -Uri $GraphUrl -Method 'GET' -Headers $Header -ContentType "application/json" 
    $DriveID = $Result.value| Where-Object {$_.webURL -eq $LibraryURL } | Select-Object id -ExpandProperty id
    
    If ($DriveID -eq $null){
    
        Throw "SharePoint Library under $LibraryURL could not be found."
    }
    
    #endregion
    
    #region download file
    
    $Url  = "https://graph.microsoft.com/v1.0/drives/$DriveID/items/root:/$($FileName)"
    
    $Response =  Invoke-RestMethod -Uri $Url -Headers $Header -Method Get -ContentType 'multipart/form-data' 
    
    Invoke-WebRequest -Uri $Response.'@microsoft.graph.downloadUrl' -OutFile $Path
    
    #endregion

    At the end you will receive the following response as example

    As you can see, the file was downloaded successfully from the SharePoint Library

    Screenshot of the downloaded file from SharePoint using Graph API
    Result of download files from SharePoint using Graph

    Further Reference

    You might be also interested in following articles, which are related to MS Graph API:

    Security of app registration in Entra ID | SPO Scripts

    Create SharePoint list items using Graph API (PowerShell) (workplace-automation.com/)

    How to get SharePoint List Items with Graph API (PowerShell) | SPO Scripts

  • How to upload files to SharePoint using Graph API (PowerShell)

    How to upload files to SharePoint using Graph API (PowerShell)

    Uploading files to SharePoint is a common use case, when we are integrating 3rd party systems with SharePoint. In my previous articles, I have been explaining how you can upload files to SharePoint using PNP module. In this article, I want to show you how you can achieve upload files to SharePoint using Graph API.

    Note: This method works for files, where the size is maximum 4 MB.

    In the beginning, we will create an Azure Enterprise Application in Azure Active Directory. Then we will grant the created Enterprise Application the permission to interact with selected sites. At the end, I will share a PowerShell script to upload files to the SharePoint using Graph API.

    What do I need to upload files to SharePoint using Graph API?

    To upload a file to SharePoint using Graph API, you need the following prerequisites fulfilled:

    • You need your global administrator in your organization to grant the sites.selected permission for an Azure Enterprise Application
    • You need to install PNP PowerShell module, to grant the Enterprise Application the permission to upload files to the specific SharePoint Site

    How to create the Enterprise Application to upload Files to SharePoint?

    In the beginning it is import to understand, which permission the Enterprise Application needs so that we can upload files to SharePoint using Graph API.

    1. Browse to Azure Active Directory Portal
    2. Create an App Registration with Sites.Selected permissions
    3. Create and note down credentials for the App Registration


    I will explain how to do it step-by-step.

    Browse to Azure Active Directory Portal

    Open https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade in your browser.

    If you have the global admin rights, I recommend authenticating with that account, so that you can directly grant your enterprise application the permission. Otherwise, you need to reauthenticate or ask your administrator to grant your enterprise application the permissions.

    Create an App Registration with Sites.Selected permissions

    Browse to the App Registration blade

    Screenshot of the App registrations shortcut

    Click on new registration

    Screenshot of new enterprise app registration

    Define for the App a meaningful name, which follows your organization standards (Different admins should recognize what the purpose for this app is) and register it.

    Screenshot on how to create the App registration in MS Azure

    Browse to API permissions to grant your app registration the permission to upload files to SharePoint using Graph API.

    Screenshot of configuration blade for App API permissions

    Click on Add a permission

    Screenshot of how to add the API permission to the App registration

    Now choose Microsoft Graph

    Chose of Microsoft Graph Permission

    If you want your application to work in the background (Without any user authentication), you need to choose Application permission. As my intention is to show you how to automate the process, I am sharing with you the application permission way.

    Screenshot of Application permission path of API permission

    Now search for Sites.Selected and click on add permissions.

    If you are signed in with a user account with global administrator privileges, you can grant administrator admin consent for your tenant. In other case, you either need to sign in with the global administrator account or you have to ask your administrator to grant your app registration the permission.

    Screenshot of grant admin consent for tenant of the app registration

    Create Secret for the App Registration

    To authenticate with your enterprise application, you need to either upload a certificate or create a secret for your enterprise application. In this case I am creating a secret.

    Browse to Certificates & secrets

    Screenshot of Certificates & secrets blade

    Screenshot on how to create a client secret

    For the description, I think it makes sense to define which application is going to use your client secret. For the duration, I would go with the recommendation of Microsoft, as you might have lost this application out of sight in 24 months, which is the maximum duration for a client secret.

    Screenshot of creation of app secret

    Now note down, what you see under value, you can only see it now.

    Screenshot of app secret

    With that last step, your Enterprise application has the right permissions on Azure Active Directory. In the next step you need to grant your enterprise Application the permission to write into the specific SharePoint site.

    How to grant the App Registration Write Permissions for a Selected SharePoint Site?

    In order to grant the app registration the permission, you need to ensure that PNP Module is installed on your client and that you are allowed to use it.

    If you have not yet installed it, check the following documentation:

    Connect to SharePoint with PowerShell | SharePoint Online (workplace-automation.com/)

    If both conditions are applying, you can use this code to grant your App registration right permission to write in the site.

    You can get your App ID by browsing to the overview page of your app registration.

    Screenshot of Application (client) ID

    Import-Module PnP.PowerShell
    
    $AppID = "e0b8aefa-cb52-4bda-93a0-7d87120bcdbb"
    $AppRegistrationName = "SP_Sites.Selected_SalesandMarketing"
    
    $DisplayNameofSitePermission = "Enterprise Application $AppRegistrationName"
    $SiteURL = "https://m365x323732.sharepoint.com/sites/SalesAndMarketing"
    
    
    Connect-PnPOnline -Url $SiteURL -Interactive
    Grant-PnPAzureADAppSitePermission -AppId $AppID -DisplayName $DisplayNameofSitePermission -Site $SiteURL -Permissions Write

    You will be asked to authenticate.

    Screenshot of authentication prompt

    At the end, your app registration has write permissions.

    Screenshot of App registration to write permissions to SharePoint Site

    How to Upload Files to SharePoint using Graph API?

    As we have created an app registration and gave it the permission to write to a selected site, we can use to upload files to SharePoint using Graph API. In my example, I want to upload a picture to the SharePoint Library Shared Documents. Make sure, that you have adjusted the parameters and have the client secret handy, which we have created in the previous steps.

    When you run the code, you will be asked to provide the client secret for your app registration.

    Screenshot of credential prompt
    Param (
        $Tenant = "m365x323732",
        $AppID = "e0b8aefa-cb52-4bda-93a0-7d87120bcdbb",
        $SiteID = "e35cee33-6d10-4e2c-a83b-496a26062ad3",
        $LibraryURL = "https://m365x323732.sharepoint.com/sites/SalesAndMarketing/Shared%20Documents",
        $Path = "C:\Users\Serkar\Desktop\security.png"
    )
    
    $AppCredential = Get-Credential($AppID)
    
    #region authorize
    $Scope = "https://graph.microsoft.com/.default"
    
    $Body = @{
        client_id = $AppCredential.UserName
        client_secret = $AppCredential.GetNetworkCredential().password
        scope = $Scope
        grant_type = 'client_credentials'
    }
    
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
    $Access_token = $AuthorizationRequest.Access_token
    
    $Header = @{
        Authorization = $AuthorizationRequest.access_token
        "Content-Type"= "application/json"
    }
    #endregion
    
    #region get drives
    
    
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives"
    
    $BodyJSON = $Body | ConvertTo-Json -Compress
    $Result = Invoke-RestMethod -Uri $GraphUrl -Method 'GET' -Headers $Header -ContentType "application/json" 
    $DriveID = $Result.value| Where-Object {$_.webURL -eq $LibraryURL } | Select-Object id -ExpandProperty id
    
    If ($DriveID -eq $null){
    
        Throw "SharePoint Library under $LibraryURL could not be found."
    }
    
    #endregion
    
    #region upload file
    
    $FileName = $Path.Split("\")[-1]
    $Url  = "https://graph.microsoft.com/v1.0/drives/$DriveID/items/root:/$($FileName):/content"
    
    Invoke-RestMethod -Uri $Url -Headers $Header -Method Put -InFile $Path -ContentType 'multipart/form-data' -Verbose
    #endregion 

    At the end you will receive the following response as example

    VERBOSE: PUT with -1-byte payload
    VERBOSE: received -1-byte response of content type application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8
    
    
    @odata.context               : https://graph.microsoft.com/v1.0/$metadata#drives('b%21M-5c4xBtLE6oO0lqJgYq04f6JqJ_iTlEhBdXmkuqxRI4cWqlVo8-QKlAJO6KoBgT')/items/$entity
    @microsoft.graph.downloadUrl : https://m365x323732.sharepoint.com/sites/SalesAndMarketing/_layouts/15/download.aspx?UniqueId=9f900d6c-d023-41cc-8839-61f079916c03&Translate=fals
                                   e&tempauth=eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAvbTM2NXgzMjM3MzIuc2hhcmVwb2ludC5jb21AOG
                                   I5Y2ZmMzQtNjg4YS00YTkzLThhZDMtMjNjYTQ3ZWU2ZTcyIiwiaXNzIjoiMDAwMDAwMDMtMDAwMC0wZmYxLWNlMDAtMDAwMDAwMDAwMDAwIiwibmJmIjoiMTY3MjgyMjg4MSIsImV4cCI6IjE
                                   2NzI4MjY0ODEiLCJlbmRwb2ludHVybCI6IjYrUUtpd1NldjBJdksyUFkwS2wyV0YveWNLSnYxQkdPc1RFb1pWclRyems9IiwiZW5kcG9pbnR1cmxMZW5ndGgiOiIxNDYiLCJpc2xvb3BiYWNr
                                   IjoiVHJ1ZSIsImNpZCI6IlpUSTFaakE0WTJJdE5XUTRPUzAwTldRd0xXSmtPVEV0WlRnMFpEUmhZVFJrTW1VMyIsInZlciI6Imhhc2hlZHByb29mdG9rZW4iLCJzaXRlaWQiOiJaVE0xWTJWb
                                   E16TXRObVF4TUMwMFpUSmpMV0U0TTJJdE5EazJZVEkyTURZeVlXUXoiLCJhcHBfZGlzcGxheW5hbWUiOiJTUF9TaXRlcy5TZWxlY3RlZF9TYWxlc2FuZE1hcmtldGluZyIsIm5hbWVpZCI6Im
                                   UwYjhhZWZhLWNiNTItNGJkYS05M2EwLTdkODcxMjBiY2RiYkA4YjljZmYzNC02ODhhLTRhOTMtOGFkMy0yM2NhNDdlZTZlNzIiLCJyb2xlcyI6InNlbGVjdGVkc2l0ZXMiLCJ0dCI6IjEiLCJ
                                   1c2VQZXJzaXN0ZW50Q29va2llIjpudWxsLCJpcGFkZHIiOiIyMC4xOTAuMTkwLjEwMSJ9.c0kydmY4eUFWS2lvWmJkTG1yTjJGbmV0SkVHVHRtdjNZWHppbm1SKytTRT0&ApiVersion=2.0
    createdDateTime              : 2023-01-04T09:01:21Z
    eTag                         : "{9F900D6C-D023-41CC-8839-61F079916C03},1"
    id                           : 01P5GC6MTMBWIJ6I6QZRAYQOLB6B4ZC3AD
    lastModifiedDateTime         : 2023-01-04T09:01:21Z
    name                         : security.png
    webUrl                       : https://m365x323732.sharepoint.com/sites/SalesAndMarketing/Shared%20Documents/security.png
    cTag                         : "c:{9F900D6C-D023-41CC-8839-61F079916C03},2"
    size                         : 129678
    createdBy                    : @{application=; user=}
    lastModifiedBy               : @{application=; user=}
    parentReference              : @{driveType=documentLibrary; driveId=b!M-5c4xBtLE6oO0lqJgYq04f6JqJ_iTlEhBdXmkuqxRI4cWqlVo8-QKlAJO6KoBgT; id=01P5GC6MV6Y2GOVW7725BZO354PWSELRRZ; 
                                   path=/drives/b!M-5c4xBtLE6oO0lqJgYq04f6JqJ_iTlEhBdXmkuqxRI4cWqlVo8-QKlAJO6KoBgT/root:}
    file                         : @{mimeType=image/png; hashes=}
    fileSystemInfo               : @{createdDateTime=2023-01-04T09:01:21Z; lastModifiedDateTime=2023-01-04T09:01:21Z}
    image                        : 
    shared                       : @{scope=users}
    
    
    
    Screenshot of the response

    As you can see, the file was uploaded successfully to the SharePoint Library

    Screenshot of the uploaded files to SharePoint using Graph API
     Screenshot of the picture in the SharePoint Library

    How to Upload Files to a Folder in SharePoint using Graph API?

    In order to upload files to folders, you just need to make sure that your URI contains the folder structure after root:/.
    In my example below, I uploaded apicture to the Subfolder folder.

    $Url = "https://graph.microsoft.com/v1.0/drives/$DriveID/items/root:/General/Subfolder/$($FileName):/content"
    
    Param (
        $Tenant = "m365x04995906",
        $AppID = "3669592a-9085-4f09-8c03-2b2223aa002c",
        $SiteID = "0a749590-8778-4779-808a-3bbb9bc1a5e1",
        $LibraryURL = "https://m365x04995906.sharepoint.com/sites/Remoteliving/Shared%20Documents",
        $Path = "C:\Users\Serka\OneDrive\Desktop\pngs\00003.jpg",
        $Folder = "General/Subfolder"
    )
    
    #$AppCredential = Get-Credential($AppID)
    
    #region authorize
    $Scope = "https://graph.microsoft.com/.default"
    
    $Body = @{
        client_id = $AppCredential.UserName
        client_secret = $AppCredential.GetNetworkCredential().password
        scope = $Scope
        grant_type = 'client_credentials'
    }
    
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
    $Access_token = $AuthorizationRequest.Access_token
    
    $Header = @{
        Authorization = $AuthorizationRequest.access_token
        "Content-Type"= "application/json"
    }
    #endregion
    
    #region get drives
    
    
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives"
    
    $BodyJSON = $Body | ConvertTo-Json -Compress
    $Result = Invoke-RestMethod -Uri $GraphUrl -Method 'GET' -Headers $Header -ContentType "application/json" 
    $DriveID = $Result.value| Where-Object {$_.webURL -eq $LibraryURL } | Select-Object id -ExpandProperty id
    
    If ($DriveID -eq $null){
    
        Throw "SharePoint Library under $LibraryURL could not be found."
    }
    
    #endregion
    
    #region upload file
    
    $FileName = $Path.Split("\")[-1]
    $Url = "https://graph.microsoft.com/v1.0/drives/$DriveID/items/root:/$Folder/$($FileName):/content"
    
    Invoke-RestMethod -Uri $Url -Headers $Header -Method Put -InFile $Path -ContentType 'multipart/form-data' -Verbose
    #endregion 

    Once executed, you’ll get back following response:

    VERBOSE: HTTP/1.1 PUT with 232877-byte payload
    VERBOSE: received -byte response of content type application/json
    VERBOSE: Content encoding: utf-8
    
    @odata.context               : https://graph.microsoft.com/v1.0/$metadata#drives('b%21kJV0CniHeUeAiju7m8Gl4ZmfCOoRAXJNrYB9wjbkfZ-Vmuw3EELGQ7bZlNIfSaf4')/items/$entity
    @microsoft.graph.downloadUrl : https://m365x04995906.sharepoint.com/sites/Remoteliving/_layouts/15/download.aspx?UniqueId=2c3c2e98-5be4-4ce2-8a81-2c0d4bab00b4&Translate=false&tempauth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAvbTM2NXgwNDk5NTkwNi5zaGFyZXBvaW50LmNv 
                                   bUAxZjc5NWU5NS1jMDZiLTQxMDktOTI0ZS0zNTY5ZmRkZjQ5OWYiLCJpc3MiOiIwMDAwMDAwMy0wMDAwLTBmZjEtY2UwMC0wMDAwMDAwMDAwMDAiLCJuYmYiOiIxNjk3NDQ0MDk5IiwiZXhwIjoiMTY5NzQ0NzY5OSIsImVuZHBvaW50dXJsIjoiWjA4ZkI5NTdNQklCckgzRUg4VHp1N0RuT3lTWVhCMHQ4VE5zZTNvNmMvMD0iLCJlbmRwb2ludHVybExlbmd0aCI6IjE0MyIsImlzbG 
                                   9vcGJhY2siOiJUcnVlIiwiY2lkIjoiWktRTFZjNHhUMEt2RlF2YSsxMjZJZz09IiwidmVyIjoiaGFzaGVkcHJvb2Z0b2tlbiIsInNpdGVpZCI6Ik1HRTNORGsxT1RBdE9EYzNPQzAwTnpjNUxUZ3dPR0V0TTJKaVlqbGlZekZoTldVeCIsImFwcF9kaXNwbGF5bmFtZSI6IlNQU2l0ZXNfUmVhZFdyaXRlQWxsIiwibmFtZWlkIjoiMzY2OTU5MmEtOTA4NS00ZjA5LThjMDMtMmIyMjIz 
                                   YWEwMDJjQDFmNzk1ZTk1LWMwNmItNDEwOS05MjRlLTM1NjlmZGRmNDk5ZiIsInJvbGVzIjoiYWxsc2l0ZXMud3JpdGUiLCJ0dCI6IjEiLCJpcGFkZHIiOiIyMC4xOTAuMTkwLjk5In0.2EMXEM184-nAFJnbOJy_PM8q5YKvOK66IoqggTX0g_E&ApiVersion=2.0
    createdDateTime              : 16.10.2023 08:14:59
    eTag                         : "{2C3C2E98-5BE4-4CE2-8A81-2C0D4BAB00B4},1"
    id                           : 01NLC4VWMYFY6CZZC34JGIVAJMBVF2WAFU
    lastModifiedDateTime         : 16.10.2023 08:14:59
    name                         : 00003.jpg
    webUrl                       : https://m365x04995906.sharepoint.com/sites/Remoteliving/Shared%20Documents/General/Subfolder/00003.jpg
    cTag                         : "c:{2C3C2E98-5BE4-4CE2-8A81-2C0D4BAB00B4},2"
    size                         : 232877
    createdBy                    : @{application=; user=}
    lastModifiedBy               : @{application=; user=}
    parentReference              : @{driveType=documentLibrary; driveId=b!kJV0CniHeUeAiju7m8Gl4ZmfCOoRAXJNrYB9wjbkfZ-Vmuw3EELGQ7bZlNIfSaf4; id=01NLC4VWOFX4E7TTHLCNB256DE3BDS7OML; name=Subfolder; path=/drives/b!kJV0CniHeUeAiju7m8Gl4ZmfCOoRAXJNrYB9wjbkfZ-Vmuw3EELGQ7bZlNIfSaf4/root:/General/Subfolder;
                                   siteId=0a749590-8778-4779-808a-3bbb9bc1a5e1}
    file                         : @{mimeType=image/jpeg; hashes=}
    fileSystemInfo               : @{createdDateTime=16.10.2023 08:14:59; lastModifiedDateTime=16.10.2023 08:14:59}
    image                        : 
    shared                       : @{scope=users}

    Further Reference

    You might be also interested in following articles, which are related to MS Graph API:

    Security of app registration in Azure Active Directory | SPO Scripts

    Create SharePoint list items using Graph API (PowerShell) (workplace-automation.com/)

    How to get SharePoint List Items with Graph API (PowerShell) | SPO Scripts

  • Create SharePoint list items using Graph API (PNP.PowerShell)

    Create SharePoint list items using Graph API (PNP.PowerShell)

    In this article, I want to show you how you can create SharePoint list items using Graph API.

    Prerequistes

    Step 1: Configure the Azure Enterprise Application

    I am following the least privilege approach and grant only the necessary permission for the app registration to create SharePoint list items using Graph API.

    Hence, I have created an App registration with following permissions:

    Permission NameType
    Sites.Selected Application
    User.ReadDelegated
    Application Registration in Microsoft Azure for reading SharePoint List Items

    If you don’t know how to create it, follow my next steps, otherwise if you are familiar with it, you can also skip to the Step 2 – Grant the Enterprise Application the Permission.

    1. Browse to Azure Portal and Search for Application Registrations and click on New registration

    Create a new Azure App registration Screenshot

    2. Give the App a meaningful name, which follows your organization standards (Different admins should recognize what the purpose for this app is) and Register it

    Registration of new App registration in Azure Portal

    3. Note down the Application ID and go to Certificates & Secrets

    Display of Application Registration in Azure Portal

    4. Create a new client secret or upload a certificate (I will show the secret approach)

    Creation of new client secret in Azure Portal

    5. Also, here a meaningful name is supportive for other colleagues. For the duration, it makes sense to go with a reasonable duration. I would go with the recommendation of Microsoft as you might have lost this application out of sight in 24 months, which is the maximum duration for a client secret.

    Creation of client secret for an App registration


    6. Now you will have ONE chance to note down the client secret. Treat it like a password. Depending on your App Permission your App might be powerful. Hence you should save for instance in a Password Manager.

    Client Secret Exposure for App registration

    7. Now Click on API permissions on the left navigation pane and add a permission for Microsoft Graph

    Adding Permission for Microsoft Graph

    8. Add the Application Permission Sites.Selected if you want the code run in the background without a signed-in user.

    API Permission for Application Permissions
    Sites.Selected Graph Permissions

    9. Once you added that, you will need to consent the permission from a global administrator.

    Not granted permissions for sites.selected

    Granted permissions look like this:

    Granted app registration permissions

    That’s it. You created an Azure App registration with Sites.Selected permission, where you need now to grant the permissions for the specific site.

    Step 2: Grant Enterprise application write permissions for SharePoint site

    For this step, you need to ensure that PNP Module is installed on your client and that you are allowed to use it.

    If both conditions are applying, you can use this code to grant Enterprise App, created in Step 1 the right permission for the site. In this case, I am granting a write role.

    Import-Module PnP.PowerShell
    
    $AppID = "9ea2120f-288c-47b6-8895-31e0fb4d9211"
    
    $DisplayNameofSitePermission = "Enterprise Application SP_Access_SharePoint_List_SalesAndMarketing_Write"
    $SiteURL = "https://m365x323732.sharepoint.com/sites/SalesAndMarketing"
    
    
    Connect-PnPOnline -Url $SiteURL -Interactive
    Grant-PnPAzureADAppSitePermission -AppId $AppID -DisplayName $DisplayNameofSitePermission -Site $SiteURL -Permissions Write

    You will need to log in with an account, which has access to the site.

    After that you will see, that the Enterprise Application has now write access to the Site.

    Screenshot of write permissions for Enterprise Application to create SharePoint list items using Graph API

    Step 3: Create SharePoint list items using Graph API with PowerShell

    As the enterprise application has now the permission to write contents to the designated SharePoint Site, you are able create SharePoint list items using Graph API.

    For this we need the app credentials and the site id of the site in which you want to create SharePoint list items using Graph API.

    Param (
        $AppID = "9ea2120f-288c-47b6-8895-31e0fb4d9211",
        $Scope = "https://graph.microsoft.com/.default",
        $Tenant = "m365x323732",
        $SiteID = "e35cee33-6d10-4e2c-a83b-496a26062ad3",
        $ListTitle = "Product%20List"
    )
    
    Import-Module PnP.PowerShell
    $AppCredential = Get-Credential($AppID)
    
    
    #region authorize
    $Body = @{
        client_id = $AppCredential.UserName
        client_secret = $AppCredential.GetNetworkCredential().password
        scope = $Scope
        grant_type = 'client_credentials'
    }
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body
    $Access_token = $AuthorizationRequest.Access_token
    
    $Header = @{
        Authorization = $AuthorizationRequest.access_token
        "Content-Type"= "application/json"
    }
    #endregion
    
    
    #region create items
    
    $Body = @{
    	fields = @{
    		Title = "Test"
    	}
    }
    
    
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/lists/$ListTitle/items"
    
    
    $BodyJSON = $Body | ConvertTo-Json -Compress
    Invoke-RestMethod -Uri $GraphUrl -Method 'POST' -Body $BodyJSON -Headers $Header -ContentType "application/json" 
    
    
    #endregion 

    As you can see the item with the title Test was created in the SharePoint List Product List.

    Screenshot of the result "create SharePoint list items using Graph API"

    Further Reference

    3 of the most important SharePoint PowerShell Modules and Snappins

    Access SharePoint via Graph API in PowerShell

    Add items to SharePoint Online lists with Powershell

    Microsoft Graph overview – Microsoft Graph | Microsoft Learn

    Working with SharePoint sites in Microsoft Graph – Microsoft Graph v1.0 | Microsoft Learn