Calling POST REST API in powershell with headers

In some cases we need to call POST REST API using Powershell.

Let’s go through sample code to get to know how it is done using Powershell.

In this Article we will go through below topics.

  • Create sample Web API
  • Invoke Web API in Powershell

Create Sample Web API

  1. Create ASP.NET Core Web Application

  1. Select API option

  1. Once project created we can see default values controller as below

We need our API to accept some Data. So we will create Modal class for that

  1. Create Modals Folder

  1. Create SampleData class under Modals Folder

  1. Add Sample properties to the class. I created Value1 and Value2 as string type.

  1. Implement API method in ValuesController as below.
[Route(“TestMethod”)]
[HttpPost]
public ActionResult TestMethod(SampleData data)
{
// Do what ever with Data
var authKey = Request.Headers[“AuthKey”];

return Ok();

}

Invoke Web API in Powershell

  1. Open Powershell ISE and write following codes to invoke REST API.

 

  • Api url
$apiUri = “https://localhost:44326/api/values/TestMethod”
  • POST Body Data Object

 

$data = @{
‘Value1’ = “val1”
‘Value2’ = “val2”
}
  • Convert POST BODY data to json format
$requestBody = $data | ConvertTo-Json -Compress
  • Create request headers object
$requestHeaders = @{‘AuthKey’ = ‘sampleauth’}
  • Use Powershell Invoke-RestMethod with parameter as below
Invoke-RestMethod -Method Post -Uri $apiUri -Body $requestBody -ContentType “application/json” -Headers $requestHeaders
  1. Put break point on TestMethod and Run the API project in debug mode
  2. Run the Powershell snippet in Powershell ISE

  1. Breakpoint will be hit and we can see the data we passed.

  1. Once you step over to “authkey” line we can see “AuthKey” header value

 

So this is how we call POST REST API end point in Powershell. ☺

Advertisements

I am a passionate software developer. I develop software using microsoft technologies and other trending web technologies. currently works at sitecore as a developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s