Call REST API Methods in SharePoint Online from PowerShell

Requirement: Call SharePoint Online REST API from PowerShell.

PowerShell to Call a REST API method in SharePoint Online

For those unfamiliar with the concept, REST stands for Representational State Transfer and is an architecture that can provide interoperability between computer systems over a network such as the Internet. The REST API is a web service that provides SharePoint data and functionality access. It can be used for many different purposes, such as building custom applications, creating one-off scripts for automating tasks, or integrating with other systems. You can use any programming language that supports HTTP requests and responses. This blog post will show you how to call the SharePoint Online REST API from PowerShell and return results in JSON format.

Here is how to call SharePoint Online REST API using PowerShell:

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Function Get-SPOUserProfileProperty ($SiteURL, $UserID)
{
    #Setup Credentials to connect
    $Cred = Get-Credential

    #Connect to Site
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
    $Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
    $Context.ExecuteQuery()    

    #Frame REST API URL
    $RequestUrl = "$($SiteUrl)/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='i:0%23.f|membership|$($UserID)'"
    $AuthenticationCookie = $Context.Credentials.GetAuthenticationCookie($SiteUrl, $true)
    $WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
    $WebSession.Credentials = $Context.Credentials
    $WebSession.Cookies.SetCookies($SiteUrl, $AuthenticationCookie)
    $WebSession.Headers.Add("Accept", "application/json;odata=verbose")

    #Invoke Rest Method
    $Result = Invoke-RestMethod -Method Get -WebSession $WebSession -Uri $RequestURL
    Return ($Result.d.userprofileproperties.results)
}

#Set Parameters
$SiteURL="https://Crescent.sharepoint.com" 
$UserID="Salaudeen@TheCrescentTech.com"

#Call the function to get user profile properties
Get-SPOUserProfileProperty -SiteUrl $SiteUrl -UserID $UserID | Select Key, Value

This retrieves all user profile properties of a given user

call sharepoint online rest api from powershell

SharePoint Online: PnP PowerShell to Call REST API

We can invoke a REST API method from PnP PowerShell with Invoke-PnPSPRestMethod:

#Parameters
$SiteURL= "https://crescent.sharepoint.com/sites/Marketing"

#Connect to the Site
Connect-PnPOnline -Url $SiteURL -Interactive 

#Define the Rest Method
$RestMethodURL = $SiteURL+'/_api/web/lists?$select=Title' 

#Invoke Rest Call to Get All Lists
$Lists = Invoke-PnPSPRestMethod -Url $RestMethodURL
$Lists.value

Please note, REST API methods are case-sensitive! ($Lists.value and $Lists.Value is not the same.)

Call REST API and Import Data to SharePoint List

In another scenario, I had to pull the data from Crowdstrike REST APIs and add the data to SharePoint Online lists.

#Set connection parameters
$client_id = "076f1qed3b4249e9b15cc1bf3ca11ff2"
$client_secret = "S19s5P3Zq7riLw22236TH3cxXXVeNhzdQ4bnalj0x"
$OAuthTokenEndpoint = "https://api.eu-1.crowdstrike.com/oauth2/token"
$RESTEndPoint = "https://api.eu-1.crowdstrike.com/devices/entities/devices/v2?offset=0&limit=5000&sort=status.desc"

#Config Variables for List
$SiteURL = "https://Crescent.sharepoint.com/sites/Monitoring"
$ListName = "CrowdStrike Hosts Report"

$AuthBody = @{
    client_id     = $client_id
    client_secret = $client_secret
    grant_type    = "client_credentials"
}

#Get the Bearer Token
Try { 
    $TokenRequest = Invoke-WebRequest -Method Post -Uri $OAuthTokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $AuthBody -UseBasicParsing -ErrorAction Stop 
}
Catch { 
    Write-Host "Unable to get the access token, aborting..."; Return 
}

#The Token endpoint returns a JSON containing the bearer token
$Token = ($tokenRequest.Content | ConvertFrom-Json).access_token

#Frame Authentication header
$AuthHeader = @{
   'Authorization'="bearer $Token"
   'accept' = "application/json"
}

#Call a REST API with the bearer token in the header
$Hosts = Invoke-WebRequest -Headers $AuthHeader -Uri $RESTEndPoint -UseBasicParsing

#Get the "Resources" from the JSON
$Resources = ($Hosts.Content | ConvertFrom-Json).Resources

#Frame Authentication header
$Header = @{
   'Authorization'="bearer $Token"
   'accept' = "application/json"
   'Content-Type'= 'application/json'
}

$Body = @{'ids' = $Resources} | ConvertTo-Json

$RESTEndPoint = "https://api.eu-1.crowdstrike.com/devices/entities/devices/v2"

$Response = Invoke-WebRequest -Method POST -Uri $RESTEndPoint -Headers $Header -Body $Body

#Get Hosts Data
$HostsDataCollection = ($Response.Content | ConvertFrom-Json).Resources

Try {
    #Connect to the Site
    Connect-PnPOnline -URL $SiteURL -Interactive

    #Clear all items in the list
    Get-PnPList -Identity $ListName | Get-PnPListItem -PageSize 100 -ScriptBlock { Param($items) Invoke-PnPQuery } | ForEach-Object {$_.Recycle() }

    #Loop through each Row in the REST Response Add Item to SharePoint List
    ForEach($HostData in $HostsDataCollection)
    {
        #Frame the List Item to update
        $ItemValue = @{}           
        $AllFields = $HostData.PSObject.Properties | Select -ExpandProperty Name
        ForEach($Row in $HostData.PSObject.Properties)
        {
            #Get Source Field Value and add to Hashtable
            If($Row.TypeNameOfValue -eq "System.Object[]")
            {
                $ItemValue.Add($Row.Name,$Row.Value -join ",")
            }
            Else
            {
                $ItemValue.Add($Row.Name,$Row.Value)
            }
        }
        Write-host "Adding List item with values:"

        #Add New List Item
        Add-PnPListItem -List $ListName -Values $ItemValue | Out-Null
     }

}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

5 thoughts on “Call REST API Methods in SharePoint Online from PowerShell

  • When I try to call rest method it returns null in powershell but it shows the values in the web ( when I check the uri with browser).
    How can i get the values in powershell as well?
    For some fields it showing encrypted data. How can i get the original data?
    Please let me know if anyone knows.

    Reply
  • Hello, my Share Point site is MFA enable. (legacy authentication disabled) And AppID and AppPassword isn’t an option. Is there a way to get around this $WebSession.Credentials = $Context.Credentials piece of the code? I keep getting a 401 authentication error.

    Reply
  • Unfotunately no. Link you shared is conencting using Pnp Powershell.

    We need way to call Sharepoint rest API using APp ID and Secret.

    Reply
  • IS there way to make this Unattended i.e. instead of hardcoding with username password , use AppID and Secrete to make calls? (I tried and credential object is null)

    Reply
    • You can hard-code any Non-MFA accounts as:

          #User Name Password to connect 
          $AdminUserName = "salaudeen@crescent.com"
          $AdminPassword = "YOUR-PASSWORD"
      
          #Prepare the Credentials
          $SecurePassword = ConvertTo-SecureString $AdminPassword -AsPlainText -Force
          $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminUserName, $SecurePassword
      

      Connecting with AppID and AppPassword is also possible. How to Connect to SharePoint Online with AppID and AppPassword using PowerShell?

      Reply

Leave a Reply

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