2

I currently use the below PowerShell script to shorten any URL via the Bitly V3 API. I am hoping someone can help to do the same thing using the Bitly V4 API.

function New-ShortURL {
    param (
            [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
            $URL
        )
    #https://app.bitly.com API
    $OAuthToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    $MyURL=Invoke-WebRequest -Uri https://api-ssl.bitly.com/v3/shorten -Body @{access_token=$OAuthToken;longURL=$URL} -Method Get
    $MyURLjson = $MyURL.Content | convertfrom-json
    $MyURLjson.data.url
}
2
  • have you read the documentation on how to migrate from v3 to v4? Commented Feb 26, 2020 at 16:43
  • Yes I did. I wasn't able to figure it out. Commented Feb 26, 2020 at 20:52

1 Answer 1

2

Reading through the documentation on changes to v4, it states,

Previous versions of the API used a query parameter to submit the token. This is no longer applicable in v4.0. Tokens should be made using the OAuth Bearer Token specification, using the Authorization header in the request.

What that means is, you cant do this,

$body = @{access_token=$OAuthToken;longURL=$URL}

instead, you have to put the access token in the header of your request.

$header = @{Authorization = "Bearer $OAuthToken"

And the method ... seems to be POST instead of GET.

Your request should look something like this,

$body = @{long_url= "https://stackoverflow.com/questions/60418169/how-to-shorten-url-with-bitly-v4-api-using-powershell?noredirect=1#comment106889121_60418169"} | convertto-json

$OAuthToken = "=========="
$header = @{Authorization="Bearer $OAuthToken"; Accept="application/json"; "Content-Type"="application/json"}

$MyURL=Invoke-WebRequest -Uri https://api-ssl.bitly.com/v4/shorten -Body $body -header $header -Method Post
$MyURLjson = $MyURL.Content | ConvertFrom-Json
$MyURLjson.link

Sign up to request clarification or add additional context in comments.

4 Comments

I just tried that script using my API token from V3. However, it doesnt return a shortened link. It says "forbidden". I need to know how to generate the OAuth2 token for this script.
Use the link to documentation I gave to see how to get the auth token. You use the same call but use -credential switch to retrieve auth token
Thank you. I was able to generate a generic API token which worked with your script. I was worried I "HAD" to use an API client key + client secret just to generate the OAuth2 token each time.
Client key and secret are listed as optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.