Using SharePoint REST API from PowerShell

In this short post I want to explain you how to use the SharePoint REST API from PowerShell, targeting a SharePoint Online site collection. As you probably know, you can do almost everything (and when I say everything, I really mean everything Smile …) using the PowerShell extensions created by my friend Erwin van Hunen, and which he kindly made available for free in the Office 365 Developer Patterns and Practices community project. just in case, you can install those PowerShell extensions from here. They are available in two flavors: v.15 that targets SharePoint on-premises, and v.16 that targets SharePoint Online.

Now, let’s say that you want to do something using low level SharePoint REST API calls within PowerShell and targeting SharePoint Online. In that case, the biggest issue is to properly provide your credentials to the target REST endpoint. In order to do that you can leverage the Connect-SPOnline cmdlet from Erwin, as well as a bunch of custom PowerShell scripting. Here is a code excerpt to accomplish a very simple task (getting the title of a library):

# Connect to SharePoint Online
$targetSite = https://.sharepoint.com/sites//
$targetSiteUri = [System.Uri]$targetSite

Connect-SPOnline $targetSite

# Retrieve the client credentials and the related Authentication Cookies
$context = (Get-SPOWeb).Context
$credentials = $context.Credentials
$authenticationCookies = $credentials.GetAuthenticationCookie($targetSiteUri, $true)

# Set the Authentication Cookies and the Accept HTTP Header
$webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$webSession.Cookies.SetCookies($targetSiteUri, $authenticationCookies)
$webSession.Headers.Add(“Accept”, “application/json;odata=verbose”)

# Set request variables
$targetLibrary = “Documents”
$apiUrl = “$targetSite” + “_api/web/lists/getByTitle(‘$targetLibrary’)”

# Make the REST request
$webRequest = Invoke-WebRequest -Uri $apiUrl -Method Get -WebSession $webSession

# Consume the JSON result
$jsonLibrary = $webRequest.Content | ConvertFrom-Json
Write-Host $jsonLibrary.d.Title

You can now adapt the authentication code to your needs, and you can call almost every REST endpoint using this technique.