Thursday, May 18, 2023
HomeSoftware TestingBe taught REST APIs And PowerShell's Invoke-RestMethod (2023)

Be taught REST APIs And PowerShell’s Invoke-RestMethod (2023)


Whether or not you’re retrieving info, submitting knowledge, or automating a process, Invoke-RestMethod might help streamline your workflow and enhance your productiveness. This text will discover use Invoke-RestMethod in PowerShell to work together with REST APIs and carry out widespread operations.

Understanding the Invoke-RestMethod Cmdlet

The Invoke-RestMethod cmdlet is a robust device in PowerShell that permits you to work together with Representational State Switch (REST) APIs. This cmdlet simplifies the method of sending HTTP/HTTPS requests to RESTful net providers and retrieving knowledge from them.

It might deal with all varieties of HTTP requests, together with GET, POST, PUT, DELETE, and PATCH, and it will possibly deal with knowledge in varied codecs resembling JSON, XML, and plain textual content. Utilizing this cmdlet, you may simply combine PowerShell scripts with RESTful net providers to automate duties and retrieve knowledge.

System Necessities for Utilizing the Invoke-RestMethod Cmdlet

  1. PowerShell model 3.0 or later put in in your machine
  2. An lively web connection, as you can be sending and receiving knowledge over the online.
  3. Another code editor like Visible Studio Code or Notepad++.

Utilizing a Easy GET request to retrieve knowledge

Utilizing a Easy GET request is without doubt one of the primary operations of REST APIs in PowerShell. The Invoke-RestMethod cmdlet is used to make the GET request to the API endpoint and retrieve knowledge.

The retrieved knowledge can then be manipulated and displayed within the PowerShell console or exported to a file. So as to use the Invoke-RestMethod cmdlet, it’s essential have the API endpoint URL, legitimate authentication credentials if required, and a primary understanding of the JSON knowledge format.

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

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

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

On this instance, we’re retrieving knowledge from the “posts” endpoint of the JSONPlaceholder API utilizing a GET request. The response knowledge is saved within the $response variable after which displayed within the console.

Authenticating APIs in PowerShell

Primary Authentication

Primary Authentication is a technique of authentication utilized by REST APIs that includes sending a username and password with each request to entry the API. This enables the API to confirm the identification of the person earlier than permitting them to entry protected assets. In PowerShell, Primary Authentication could be carried out utilizing the Invoke-RestMethod cmdlet and the -Credential parameter.

Right here’s an instance of utilizing Primary Authentication with Invoke-RestMethod in PowerShell:

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

On this instance, change “your_username” and “your_password” along with your precise credentials. The $headers variable creates a dictionary with the Authorization key set to a worth containing the Base64-encoded credentials. The -Headers parameter is used to move these headers to the API endpoint together with the GET request. The API response is saved within the $response variable.

Bearer Authentication

Bearer authentication is a technique of authentication that includes the usage of a bearer token. This token is generated by the server and is used to authenticate subsequent requests made to the server.

To make use of bearer authentication in PowerShell, you may set the Authorization header to “Bearer <token>“. For instance:

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

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

Utilizing Question Parameters to get knowledge again

Retrieving knowledge with question parameters is a typical use case when working with REST APIs in PowerShell. Question parameters are used to filter or kind the info returned from the API.

In PowerShell, you may simply add question parameters to your API requests utilizing the Invoke-RestMethod cmdlet. By specifying the question parameters within the URL, you may customise the info that’s returned from the API to fulfill your particular wants.

Right here’s an instance of utilizing question parameters to retrieve knowledge utilizing Invoke-RestMethod:

# Outline the endpoint URL with question parameters 
$url = "https://api.instance.com/orders?standing=accomplished&start_date=2022-01-01&end_date=2022-01-31" 

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

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

# View the response knowledge 
$response

On this instance, the endpoint URL accommodates question parameters standing, start_date, and end_date to filter the order knowledge. The headers include the bearer token for authentication. The Invoke-RestMethod cmdlet is used with the -Uri, -Headers, and -Methodology parameters to make the GET request.

The response knowledge is saved within the $response variable and could be considered utilizing Write-Output or different PowerShell instructions.

Knowledge Switch by way of the POST HTTP Methodology

POST Request

When working with REST APIs, it’s widespread to want to ship knowledge to the API in a POST request. That is typically achieved utilizing JSON knowledge. PowerShell makes it simple to ship JSON knowledge in a POST request utilizing the Invoke-RestMethod cmdlet.

To ship JSON knowledge, you first must create a PowerShell object that represents the info you need to ship. You may then use the ConvertTo-Json cmdlet to transform the item to JSON format.

Right here’s an instance:

# Create a PowerShell object that represents the info you need to ship
$knowledge = @{
    title = "John Smith"
    age = 30
    e-mail = "john.smith@instance.com"
}

# Convert the item to JSON format
$jsonData = $knowledge | ConvertTo-Json

# Ship a POST request with the JSON knowledge
$uri = "https://instance.com/api/customers"
$headers = @{
    "Content material-Sort" = "utility/json"
}

$response = Invoke-RestMethod -Methodology Put up -Uri $uri -Headers $headers -Physique $jsonData

On this instance, we create a PowerShell object referred to as $knowledge that accommodates three properties: title, age, and e-mail. We then use the ConvertTo-Json cmdlet to transform this object to JSON format and retailer the lead to a variable referred to as $jsonData. Lastly, we use Invoke-RestMethod to ship a POST request to the API with the JSON knowledge within the request physique.

Observe that we additionally set the Content material-Sort header to utility/json to point that we’re sending JSON knowledge within the request physique.

Invoke-RestMethod

To ship kind knowledge with Invoke-RestMethod in PowerShell, you should utilize the -Kind parameter. The -Kind parameter expects a hashtable containing key-value pairs of the shape knowledge.

Right here’s an instance:

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

On this instance, we’re sending a POST request to https://instance.com/api/form-data with kind knowledge containing a username and password area.

Tailing Relation Hyperlinks

Following relation hyperlinks in REST APIs refers to accessing associated assets by way of their hyperlinks which can be supplied within the response to a earlier API request. This system permits for the retrieval of associated knowledge with out having to make a number of API requests.

In PowerShell, this may be achieved utilizing the Invoke-RestMethod cmdlet and parsing the response physique to extract the hyperlink for the associated useful resource. The hyperlink can then be used to make one other API request to retrieve the associated knowledge.

$response = Invoke-RestMethod -Uri "https://api.instance.com/customers/1"

# Observe the "self" relation hyperlink to get extra details about the person
$person = Invoke-RestMethod -Uri $response._links.self.href

# Observe the "firm" relation hyperlink to get extra details about the person's firm
$firm = Invoke-RestMethod -Uri $person._links.firm.href

On this instance, we first make a request to the API endpoint for a person with an ID of 1. The response features a _links property that accommodates relation hyperlinks to different assets. We then use Invoke-RestMethod once more to comply with the “self” relation hyperlink to get extra details about the person and the “firm” relation hyperlink to get details about the person’s firm.

Managing Session Data

When working with REST APIs, generally it’s crucial to take care of session info between requests. PowerShell’s Invoke-RestMethod cmdlet permits us to take care of session info through the use of the -SessionVariable parameter.

The -SessionVariable parameter creates a session object that we are able to reference in subsequent Invoke-RestMethod calls. That is helpful when we have to preserve authentication info or when we have to chain a number of requests collectively that rely upon one another.

To make use of this parameter, we first must create a session variable to carry the session info. We will do that with the New-Object cmdlet and the System.Internet.CookieContainer class. For instance:

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

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

Invoke-RestMethod -Uri 'https://api.instance.com/login' -Methodology POST -Physique $physique -ContentType 'utility/json' -SessionVariable session Invoke-RestMethod -Uri 'https://api.instance.com/knowledge' -Methodology GET -SessionVariable session
Managing Session Information

By passing the -SessionVariable parameter, the session info from the primary request is saved within the $session variable and can be utilized in subsequent requests. This enables us to take care of state info throughout a number of requests.

Nullifying Session Values

To override session values, you may move them as parameters to the Invoke-RestMethod cmdlet. For instance, if you wish to set a customized user-agent header, you are able to do the next:

Invoke-RestMethod -Uri https://api.instance.com/customers -Headers @{ "Consumer-Agent" = "MyApp/1.0" }
Nullifying Session Values
Be taught REST APIs And PowerShell’s Invoke-RestMethod 8

On this instance, the -Headers parameter is used to set a customized user-agent header with the worth “MyApp/1.0”.

Exporting the Response Physique

In PowerShell, we are able to use the Invoke-RestMethod cmdlet to make HTTP requests to a REST API and retrieve the response. Generally, we could need to save the response physique to a file for additional processing or evaluation.

To avoid wasting the response physique to a file, we are able to use the Out-File cmdlet. We will move the -FilePath parameter with the specified file path and title, after which pipe the output of the Invoke-RestMethod cmdlet to Out-File. Right here’s an instance:

Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/posts/1" | Out-File -FilePath "C:dataresponse.json"
Exporting the Response Body
Be taught REST APIs And PowerShell’s Invoke-RestMethod 9

On this instance, we’re making a GET request to the JSONPlaceholder API and retrieving the response physique for the publish with ID 1. The response physique is then piped to Out-File, which saves it to a file named “response.json” within the “C:knowledge” listing.

Through the use of this method, we are able to simply save the response physique to a file and carry out additional evaluation or processing of the info.

By now, it is best to have grasped the idea of the Invoke-RestMethod cmdlet and the Relaxation APIs. For additional info and parameters, you may go to the respective web page on the Microsoft PowerShell net web page.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments