Automating API Calls with Powershell access_token?

Hello!

I’d like to use the API to replace some PDF files every day, I managed to do everything in postman, but now I would like to implement that into a powershell script.
The call for the access_token is already the first problem. In postman this call only works if I go to the authorization tab and then Get New Access Token (Relevant post: Postman API Tutorial -> 404 with access_token)
Doing the same thing in Powershell leaves me again with a 404 error:


With an access_token that I got from Postman, I was able to some basic calls without any issues. The second Problem is the part when I try to upload an actual file. Again, no problem in postman. How would powershell syntax look like for this? This is what I currently have:

“File type not allowed”

Is there any way of solving these issues? Should I be using a different language with postman export functionality? Is there a way of exporting from postman through the HTTP thing and using that somehow in powershell?
Thanks a lot for your help!

I used the Method get for my access_token call, changed to post still doesnt work. But I somehow got it working in postman, no idea what I changed tho
Edit: Shuffled some things around between header and body and now I get the token :slight_smile: Still the same problem with the media file upload :frowning:

You’re passing the path of the file up in a post request, but what you actually want to do is post up the actual file.

I’m not sure if you can do that with PowerShell, but a Google on the subject does seem to indicate that it is possible. You;d need to set the content type and then pass the actual file bytes somehow.

quick code (W10 1809)

$url          = 'http://xibo.domain.local'
$clientId     = 'lxHcmvWqPtzySgdrsk1aaMwwKwvMr2uzGSYjljDr'
$clientSecret = 'C5v5x2hVyrcOB7u5G1B5eqLxpU5eqsWnnZUPEAcLGNCMgzLbPhKuhwCgYCM5RwyXV0zxIDo8PvsHhR5AISbQ1Uf1kotO7sFvlIfuV0r0amnVjUnL4Acs5Z0e7pNBxMam0csEctdbYAczyitLDJNf952X9G4p8I5SccRWyvk9UISa5T82ukP1jry4H4oyUskAB2PbrFRumhqXQd2IEY411LGfRSTR6Vs12FUjvGtcCq7eGvaRWjB3e9q6nU0zOF'
$curlPath     = 'curl.exe'

$tmp = New-TemporaryFile
$argumentlist = "--location --request POST $($url+'/api/authorize/access_token') `
        --form client_id=$clientId `
        --form client_secret=$clientSecret '
        --form grant_type=client_credentials"
Start-Process -filepath $curlPath -argumentlist $argumentlist -wait -passthru - 
RedirectStandardOutput $tmp.FullName | Out-Null
$access_token = (Get-Content $tmp.FullName).Replace('"','').Replace('{','').Split(',')[0].Split(':')[1]
Remove-Item $tmp.FullName -Force
$access_token
2 Likes

Apologies for reviving a dead thread, though wanted to share a simpler solution:

$url = 'http://your-url'
$clientId = 'your0id'
$clientSecret = 'your0secret'
$grant = "client_credentials"
$type = 'application/x-www-form-urlencoded'
$headers = @{}
$headers.Add("Accept", "application/json")
$body = "grant_type=$grant&client_id=$clientId&client_secret=$clientSecret"
$response = Invoke-RestMethod -Uri "$url/api/authorize/access_token" -Method Post -Headers $headers -ContentType $type -Body $body
$access_token = $response.access_token

Technically, content-type is not required, though I found it not to impact results and allows for leveraging a single Invoke-RestMethod command (i.e. wrapped in a function).

While densan’s solution does work, the above is leveraging native PS. I hope this helps others.

1 Like

This is what we’re doing in PowerShell Universal - when we need to call the Xibo API we call this function first to get a bearer token.
The Cache variables will probably need to be global variables for most people

$XiboBaseURI = "http://cms-address.here"
$XiboClientID = "stringhere"
$XiboClientSecret = "bigstringhere"

function Get-XiboBearerToken {
    
    if ($cache:XiboCurrentBearerToken -and ($cache:XiboCurrentBearerTokenExpiryTime -gt (Get-Date))) {
        Write-Debug "Token exists and is valid, returning token: $cache:XiboCurrentBearerToken"
    }
    else {
        $Form = @{
            client_id     = $XiboClientID
            client_secret = $XiboClientSecret
            grant_type    = 'client_credentials'
        }
        $cache:XiboCurrentBearerToken = (Invoke-RestMethod "$XiboBaseURI/api/authorize/access_token" -Method Post -Form $Form).access_token
        $CurrentTime = Get-Date
        $cache:XiboCurrentBearerTokenExpiryTime = $CurrentTime.AddSeconds(3500)
        Write-Debug "Bearer token expires at time: $cache:XiboCurrentBearerTokenExpiryTime"
        Write-Debug "Token: $cache:XiboCurrentBearerToken"
    }   
}

I should say, if memory serves bits of this are only possible in PowerShell 7, but it’s been a while since I’ve interacted with an API using 5.1

1 Like