API - Getting 401 Unauthorised Error

Post Reply
Posts: 24
Joined: 01 May 2020, 03:06

I'm trying to get the basic API functionality working in PowerShell prior to moving onto PowerAutomate in MS 365.

I've got the login working and I'm getting a bearer and refresh token back, but I keep getting a 401 Unauthorised error when trying to get the 'applications'. This is my code:
# Set up variables
$domain = "https://REDACTED.essentialintelligence.com"
$username = "[email protected]"
$pwd = "REDACTED"
$repo = "REDACTED"

# *** LOGIN ***
$headers0 = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers0.Add("Content-Type", "application/json")
$headers0.Add("x-api-key", "$apikey")

$body = "{`n `"grantType`": `"password`",`n `"username`": `"$username`",`n `"password`": `"$pwd`"`n}"

Write-Host 'Getting token:'
$response0 = Invoke-RestMethod $domain'/api/oauth/token' -Method 'POST' -Headers $headers0 -Body $body
Write-Host 'Getting token Complete.'

# Retrieve the token
$token = $response0.bearerToken;
$token = 'Bearer ' + $token
#Write-Host $token

# *** Get Apps ***
$headers2 = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers2.Add("Content-Type", "application/json")
$headers2.Add("Authorization", $token)
$headers2.Add("x-api-key", $apikey)

#echo $headers2

$URL = $domain + '/api/essential-core/v1/repositories/' + $repo + '/applications'
#echo $URL

Write-Host 'Calling GET Applications:'
$response2 = Invoke-RestMethod $URL -Method 'GET' -Headers $headers2
$response2 | ConvertTo-Json
Write-Host 'Calling GET Applications Complete.'
I've tried breaking say the token value I then get 'forbidden' instead, if i break the apikey I get a text based Unauthorized body back(no 401), now if I break the repo ID, I get the same 401 Unauthorised error, so I'm wondering if something wrong with the URL?

Posts: 24
Joined: 01 May 2020, 03:06

Ok, this one was definitely user error!

For those that might find themselves in a similar position, don't use the viewer ID, make sure it's the repo ID!!
Post Reply