Scenario 7 - the REST API in PowerShell

The REST API appeals to developers and administrators because it is based on web standards. REST requests are HTTP requests that adhere to simple rules. In SharePoint, the REST API has been recently enhanced at a faster pace than the CSOM API.

To take advantage of the REST API through PowerShell, we are going to use an open source project from the Patterns and Practices team from Microsoft. We will cover this project in depths in the Chapter 7, Patterns and Practices PowerShell.

The SharePointPnP.PowerShell Commands project (https://github.com/SharePoint/PnP-PowerShell) contains a series of PowerShell commands that are implemented with CSOM. This is a good mix between CSOM functionality and the ease of use of PowerShell commands.

Before we get started, you can install the module using the following command:

Install-Module SharePointPnPPowerShellOnline -AllowClobber `
-Scope CurrentUser

The syntax is very similar to the SPOs but similarly to CSOM, we can target individual site collections. We establish a connection to a site collection through the Connect-PnPOnline command:

$siteUrl = 'https://mytest321.sharepoint.com'
Connect-PnPOnline $siteUrl
$ctx = (Get-PnPWeb).Context

To create a web request, we need to pass a valid cookie that we can obtain from the current context. With the credentials, we can establish a web request. The web request packages the credentials and settings that we will use to submit a request to SharePoint Online:

$creds = $ctx.Credentials
$cookies = $creds.GetAuthenticationCookie($siteUrl,$true)
$webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$webSession.Cookies.SetCookies($siteUrl, $cookies)
$webSession.Headers.Add('Accept', 'application/json;odata=verbose')

In the next script, we submit a GET request following the REST syntax to retrieve the title of the first item of the Site Assets list. The response is then parsed as a JSON object:

$restUrl = "https://mytest321.sharepoint.com/_api/web/lists/getbytitle('Site Assets')/items(1)?$select=Title"
$webRequest = Invoke-WebRequest -Uri $restUrl -Method Get -WebSession $webSession
$webRequest.Content.Replace("ID", "_ID") | ConvertFrom-Json

odata.metadata : /_api/$metadata#SP.ListData.SiteAssetsItems/@Element
...
Created : 2016-12-01T06:19:40Z
AuthorId : 1073741823
Modified : 2016-12-01T06:19:40Z
EditorId : 1073741823
...
Title : Team Site Notebook

Hopefully, with this example, you see the potential of the REST API as well as the Patterns and Practices project and it has whetted your interest so that you will continue learning.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.34.146