Interacting with a RESTful API

Interacting with REST APIs is rather easy in PowerShell; the Invoke-RestMethod cmdlet does all the heavy lifting for you. Let's view the four example calls, Create, Read, Update, and Delete, with our own API in the following example:

$jsonBody = @{
Name = 'testfile.txt'
Content = 'This is almost too easy'
} | ConvertTo-Json

$jsonBodyUpdate = @{
Name = 'testfile.txt'
Content = 'It works like a charm'
} | ConvertTo-Json

# Create
Invoke-RestMethod -Method Post -Uri http://localhost:8080/files -Body $jsonBody -ContentType application/json

# Read - Invoke-RestMethod converts from JSON automatically

# All files
Invoke-RestMethod -Method Get -Uri http://localhost:8080/files

# Specific file
Invoke-RestMethod -Method Get -Uri http://localhost:8080/files?Name=testfile.txt

# Update
Invoke-RestMethod -Method Put -Uri http://localhost:8080/files -Body $jsonBodyUpdate -ContentType application/json

# Delete
Invoke-RestMethod -Method Delete -Uri http://localhost:8080/files?Name=testfile.txt

Invoke-WebRequest returns the entire request object to you so that you can parse it yourself. This is useful when the website you are querying does not return structured JSON data. In the case of our API, we can always expect JSON, so we make use of Invoke-RestMethod. Notice in the example that the same URI is used in all cases. Sometimes a query parameter is appended; sometimes we use the JSON body.

On your Polaris host, each call uses the temporary path created when you set up your API endpoint to create, list, modify, or delete files.

The same principles you learned apply to any RESTful endpoint, such as Visual Studio Team Services, various Graph APIs, and endpoints leveraging Swagger. You can apply the learning with this sample endpoint: http://petstore.swagger.io/.

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

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