Jira API - Add Watcher

Hello :slight_smile:

I am trying to utilize the Jira Cloud API to add an watcher to an issue.
The Jira Cloud platform REST API (atlassian.com)

If i execute this code it add the user that are executing the script as an watcher - just as designed.


$pair = "$($userName):$($userPassword)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = @{
    Authorization = $basicAuthValue
    "Accept" = "application/json"
    "Content-Type" = "application/json"
}


Invoke-RestMethod -Uri "https://company.atlassian.net/rest/api/2/issue/Key-Number/watchers" -Headers $Headers -Method POST -ContentType "application/json"

But if i add an Body then it fails with an Error 400 - this is the code:


$pair = "$($userName):$($userPassword)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = @{
    Authorization = $basicAuthValue
    "Accept" = "application/json"
    "Content-Type" = "application/json"
}


$Body = @{
    accountId = '123-456-789' #This part is redacted
} | ConvertTo-Json
Invoke-RestMethod -Uri "https://company.atlassian.net/rest/api/2/issue/Key-Number/watchers" -Headers $Headers -Method POST -ContentType "application/json" -Body $Body

If i access the API URL in the browser, this is the output:

I am sure that my body is incorrect - but i cant figure out why.

Could you help?

Finally found a solution - the body needs to be a string.
So this worked:

$Body = """123-456-789"""
Invoke-RestMethod -Uri "https://company.atlassian.net/rest/api/2/issue/Key-Number/watchers" -Headers $Headers -Method POST -ContentType "application/json" -Body $Body

Thanks for sharing.

FWIW - This is less of a PS question and more of a API specific question regarding formatting. In general these forums are more for PS specific questions, so while some of us may attempt to assist, it’s really out of scope of these forums.

$Body = """123-456-789""" seems strange not sure if that was a formatting thing but I’d expect only one set of " is needed.

Completely agree this is an API question. FWIW if you’re intending to write a lot of API calls in Powershell, grab Postman which is free. It also has a handy dandy code button on the right ‘</>’ that will automatically generate code in many many languages including Powershell :wink: