fbpx

Learn REST APIs And PowerShell’s Invoke-RestMethod

Whether you’re retrieving information, submitting data, or automating a task, Invoke-RestMethod can help streamline your workflow and improve your productivity. This article will explore how to use Invoke-RestMethod in PowerShell to interact with REST APIs and perform common operations.

Understanding the Invoke-RestMethod Cmdlet

The Invoke-RestMethod cmdlet is a powerful tool in PowerShell that allows you to interact with Representational State Transfer (REST) APIs. This cmdlet simplifies the process of sending HTTP/HTTPS requests to RESTful web services and retrieving data from them.

It can handle all types of HTTP requests, including GET, POST, PUT, DELETE, and PATCH, and it can handle data in various formats such as JSON, XML, and plain text. Using this cmdlet, you can easily integrate PowerShell scripts with RESTful web services to automate tasks and retrieve data.

System Requirements for Using the Invoke-RestMethod Cmdlet

  1. PowerShell version 3.0 or later installed on your machine
  2. An active internet connection, as you will be sending and receiving data over the web.
  3. Any other code editor like Visual Studio Code or Notepad++.

Using a Simple GET request to retrieve data

Using a Simple GET request is one of the basic operations of REST APIs in PowerShell. The Invoke-RestMethod cmdlet is used to make the GET request to the API endpoint and retrieve data.

The retrieved data can then be manipulated and displayed in the PowerShell console or exported to a file. In order to use the Invoke-RestMethod cmdlet, you need to have the API endpoint URL, valid authentication credentials if required, and a basic understanding of the JSON data format.

# Set the URI endpoint for the REST API 
$uri = "https://jsonplaceholder.typicode.com/posts" 

# Invoke the GET request and store the response in a variable 
$response = Invoke-RestMethod -Uri $uri -Method Get 

# Display the response data 
$response
Using a Simple GET request to retrieve data

In this example, we’re retrieving data from the “posts” endpoint of the JSONPlaceholder API using a GET request. The response data is stored in the $response variable and then displayed in the console.

Authenticating APIs in PowerShell

Basic Authentication

Basic Authentication is a method of authentication used by REST APIs that involves sending a username and password with every request to access the API. This allows the API to verify the identity of the user before allowing them to access protected resources. In PowerShell, Basic Authentication can be implemented using the Invoke-RestMethod cmdlet and the -Credential parameter.

Here’s an example of using Basic Authentication with Invoke-RestMethod in PowerShell:

$username = "your_username" $password = "your_password" $uri = "https://api.example.com/resource" $headers = @{ Authorization = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$($username):$($password)")) } $response = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get
Basic Authentication

In this example, replace “your_username” and “your_password” with your actual credentials. The $headers variable creates a dictionary with the Authorization key set to a value containing the Base64-encoded credentials. The -Headers parameter is used to pass these headers to the API endpoint along with the GET request. The API response is stored in the $response variable.

Bearer Authentication

Bearer authentication is a method of authentication that involves the use of a bearer token. This token is generated by the server and is used to authenticate subsequent requests made to the server.

To use bearer authentication in PowerShell, you can set the Authorization header to “Bearer <token>“. For example:

$headers = @{ Authorization = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" } Invoke-RestMethod -Uri "https://api.example.com/v1/resource" -Headers $headers
Bearer Authentication

In this example, we set the Authorization header to “Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c”, which is a sample bearer token. We then use Invoke-RestMethod to make a request to the API endpoint with the specified headers.

Using Query Parameters to get data back

Retrieving data with query parameters is a common use case when working with REST APIs in PowerShell. Query parameters are used to filter or sort the data returned from the API.

In PowerShell, you can easily add query parameters to your API requests using the Invoke-RestMethod cmdlet. By specifying the query parameters in the URL, you can customize the data that is returned from the API to meet your specific needs.

Here’s an example of using query parameters to retrieve data using Invoke-RestMethod:

# Define the endpoint URL with query parameters 
$url = "https://api.example.com/orders?status=completed&start_date=2022-01-01&end_date=2022-01-31" 

# Define the headers with authorization token 
$headers = @{ Authorization = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" } 

# Make the GET request with query parameters 
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Get 

# View the response data 
$response

In this example, the endpoint URL contains query parameters status, start_date, and end_date to filter the order data. The headers contain the bearer token for authentication. The Invoke-RestMethod cmdlet is used with the -Uri, -Headers, and -Method parameters to make the GET request.

The response data is stored in the $response variable and can be viewed using Write-Output or other PowerShell commands.

Data Transfer through the POST HTTP Method

POST Request

When working with REST APIs, it’s common to need to send data to the API in a POST request. This is often done using JSON data. PowerShell makes it easy to send JSON data in a POST request using the Invoke-RestMethod cmdlet.

To send JSON data, you first need to create a PowerShell object that represents the data you want to send. You can then use the ConvertTo-Json cmdlet to convert the object to JSON format.

Here’s an example:

# Create a PowerShell object that represents the data you want to send
$data = @{
    name = "John Smith"
    age = 30
    email = "john.smith@example.com"
}

# Convert the object to JSON format
$jsonData = $data | ConvertTo-Json

# Send a POST request with the JSON data
$uri = "https://example.com/api/users"
$headers = @{
    "Content-Type" = "application/json"
}

$response = Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $jsonData

In this example, we create a PowerShell object called $data that contains three properties: name, age, and email. We then use the ConvertTo-Json cmdlet to convert this object to JSON format and store the result in a variable called $jsonData. Finally, we use Invoke-RestMethod to send a POST request to the API with the JSON data in the request body.

Note that we also set the Content-Type header to application/json to indicate that we’re sending JSON data in the request body.

Invoke-RestMethod

To send form data with Invoke-RestMethod in PowerShell, you can use the -Form parameter. The -Form parameter expects a hashtable containing key-value pairs of the form data.

Here’s an example:

$url = "https://example.com/api/form-data"
$formData = @{
    "username" = "johndoe"
    "password" = "mypassword"
}
Invoke-RestMethod -Uri $url -Method POST -Form $formData

In this example, we’re sending a POST request to https://example.com/api/form-data with form data containing a username and password field.

Tailing Relation Links

Following relation links in REST APIs refers to accessing related resources through their links that are provided in the response to a previous API request. This technique allows for the retrieval of related data without having to make multiple API requests.

In PowerShell, this can be achieved using the Invoke-RestMethod cmdlet and parsing the response body to extract the link for the related resource. The link can then be used to make another API request to retrieve the related data.

$response = Invoke-RestMethod -Uri "https://api.example.com/users/1"

# Follow the "self" relation link to get more information about the user
$user = Invoke-RestMethod -Uri $response._links.self.href

# Follow the "company" relation link to get more information about the user's company
$company = Invoke-RestMethod -Uri $user._links.company.href

In this example, we first make a request to the API endpoint for a user with an ID of 1. The response includes a _links property that contains relation links to other resources. We then use Invoke-RestMethod again to follow the “self” relation link to get more information about the user and the “company” relation link to get information about the user’s company.

Managing Session Information

When working with REST APIs, sometimes it’s necessary to maintain session information between requests. PowerShell’s Invoke-RestMethod cmdlet allows us to maintain session information by using the -SessionVariable parameter.

The -SessionVariable parameter creates a session object that we can reference in subsequent Invoke-RestMethod calls. This is useful when we need to maintain authentication information or when we need to chain multiple requests together that depend on each other.

To use this parameter, we first need to create a session variable to hold the session information. We can do this with the New-Object cmdlet and the System.Net.CookieContainer class. For example:

$session = New-Object System.Net.CookieContainer
Managing Session Information

We can then use this $session variable with the -SessionVariable parameter in subsequent Invoke-RestMethod calls. For example:

Invoke-RestMethod -Uri 'https://api.example.com/login' -Method POST -Body $body -ContentType 'application/json' -SessionVariable session Invoke-RestMethod -Uri 'https://api.example.com/data' -Method GET -SessionVariable session
Managing Session Information

By passing the -SessionVariable parameter, the session information from the first request is stored in the $session variable and can be used in subsequent requests. This allows us to maintain state information across multiple requests.

Nullifying Session Values

To override session values, you can pass them as parameters to the Invoke-RestMethod cmdlet. For example, if you want to set a custom user-agent header, you can do the following:

Invoke-RestMethod -Uri https://api.example.com/users -Headers @{ "User-Agent" = "MyApp/1.0" }
Nullifying Session Values

In this example, the -Headers parameter is used to set a custom user-agent header with the value “MyApp/1.0”.

Exporting the Response Body

In PowerShell, we can use the Invoke-RestMethod cmdlet to make HTTP requests to a REST API and retrieve the response. Sometimes, we may want to save the response body to a file for further processing or analysis.

To save the response body to a file, we can use the Out-File cmdlet. We can pass the -FilePath parameter with the desired file path and name, and then pipe the output of the Invoke-RestMethod cmdlet to Out-File. Here’s an example:

Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/posts/1" | Out-File -FilePath "C:\data\response.json"
Exporting the Response Body

In this example, we’re making a GET request to the JSONPlaceholder API and retrieving the response body for the post with ID 1. The response body is then piped to Out-File, which saves it to a file named “response.json” in the “C:\data” directory.

By using this technique, we can easily save the response body to a file and perform further analysis or processing of the data.

By now, you should have grasped the concept of the Invoke-RestMethod cmdlet and the Rest APIs. For further information and parameters, you can visit the respective page on the Microsoft PowerShell web page.