30. Communicating with RESTful APIs

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

REST stands for Representational State Transfer (sometimes spelled "ReST"). It relies on a stateless, client-server, cacheable communications protocol and mostly HTTP protocol is used. It is primarily used to build Web services that are lightweight, maintainable, and scalable. A service based on REST is called a RESTful service and the APIs which are being used for it are RESTful APIs. In PowerShell, Invoke-RestMethod is used to deal with them.

30.1: Post Message to hipChat

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$params = @{
  Uri         = 'https://your.hipchat.com/v2/room/934419/notification?auth_token=???'
  Method      = 'POST'
  Body        = @{
    color          = 'yellow'
    message        = 'This is a test message!'
    notify         = $false
    message_format = 'text'
  } | ConvertTo-Json
  ContentType = 'application/json'
}
1
Invoke-RestMethod @params

30.2: Using REST with PowerShell Objects to GET and POST many items

GET your REST data and store in a PowerShell object:

1
$Users = Invoke-RestMethod -Uri "http://jsonplaceholder.typicode.com/users"

Modify many items in your data:

1
2
3
4
$Users[ 0 ].name = "John Smith"
$Users[ 0 ].email = "[email protected]"
$Users[ 1 ].name = "Jane Smith"
$Users[ 1 ].email = "[email protected]"

POST all of the REST data back:

1
2
$Json = $Users | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri "http://jsonplaceholder.typicode.com/users" -Body $Json -ContentType 'application/json'

30.3: Use Slack.com Incoming Webhooks

Define your payload to send for possible more complex data

1
$Payload = @{ text="test string"; username="testuser" }

Use ConvertTo-Json cmdlet and Invoke-RestMethod to execute the call

1
Invoke-RestMethod -Uri "https://hooks.slack.com/services/yourwebhookstring" - Method Post -Body
1
(ConvertTo-Json $Payload)

30.4: Using REST with PowerShell Objects to Get and Put individual data

GET your REST data and store in a PowerShell object:

1
$Post = Invoke-RestMethod -Uri "http://jsonplaceholder.typicode.com/posts/1"

Modify your data:

1
$Post.title = "New Title"

PUT the REST data back

1
2
$Json = $Post | ConvertTo-Json
Invoke-RestMethod -Method Put -Uri "http://jsonplaceholder.typicode.com/posts/1" -Body $Json -ContentType 'application/json'

30.5: Using REST with PowerShell to Delete items

Identify the item that is to be deleted and delete it:

1
Invoke-RestMethod -Method Delete -Uri "http://jsonplaceholder.typicode.com/posts/1"