Home > Software design >  Using GET in PowerShell & Exporting JSON to CSV
Using GET in PowerShell & Exporting JSON to CSV

Time:11-18

I'm using the following CURL command, to read/fetch table data from an API:

curl -X GET \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -H 'Authorization: Bearer *myAccessToken*' \
    https://www.myWebsite.com/api/orders

This command/API Call returns a table in JSON format. I need to do two things with this.

[1] I need to run this in powershell. I've tried using the above code, and returns a general syntax error:

A parameter cannot be found that matches parameter name 'X'.

[2] In PowerShell, Have the JSON output converted & saved as a CSV file

Any ideas? Thanks!

CodePudding user response:

You can use Invoke-RestMethod Cmdlet to Sends an HTTP or HTTPS request to a RESTful web service.

$uri = "https://www.myWebsite.com/api/orders"
$headers = @{
    'Content-Type' = 'application/json'
    'Authorization' = 'Bearer <AccessToken>'
    'Accept'= 'application/json'
}
$response = Invoke-RestMethod -Uri $uri -Method GET -Headers $headers

PowerShell formats the response based to the data type. For JavaScript Object Notation (JSON) or XML, PowerShell converts, or deserializes, the content into [PSCustomObject] objects. So you can select the columns you want to export and pipe it into Export-Csv Cmdlet

$response | Select ColumnName1,ColumnName2 | Export-Csv -Path "filename.csv" -NoTypeInformation
  • Related