简体   繁体   中英

Jira Rest Api in Powershell

Could you help me?

I am trying to create an issue in Jira using the Powershell Invoke-WebRequest cmdlet. And I am getting 400 Bad Request error.

I was able to send a successful request using Postman, so I made sure the body syntax is correct and I have sufficient rights.

My code:

$body = @{ 
    "fields" = @{
            "project"=
            @{
                "key"= "ProjectKey"
            }
    
            "summary"= "Test"
    
            "description"= "Test"
            "issuetype" =@{
                "id"= "10705"
    
            }
            "priority"= @{
                "id"= "18"
            }
            "reporter"= @{"name"= "MyName"}
            
    }
    
    }
    
    
    $Headers =  @{
    Authorization = "Basic QWxla0Zblablablablablablabla" #I took it from Postman
    }
    
    $restapiuri = "https://jira.domain.com/rest/api/2/issue"
    
    Invoke-RestMethod -Uri $restapiuri -ContentType "application/json"  -Body $body -Method POST -Headers $Headers

for example, I can successfully execute

Invoke-RestMethod "https://jira.domain.com/rest/api/2/issue/createmeta" -Headers $Headers 

I've already spent a lot of time-solving this problem, but still can't create an issue.

Any help, please

For basic authentication with Jira SERVER, the credentials need to be supplied within the header in Base64 encoding, which you need to do before supplying it via the Powershell Invoke-WebRequest method. Here's how to do it:

$username = "The username here"
$password = "The password or token here"

# Convert the username + password into a Base64 encoded hash for basic authentication
$pair = "${username}:${password}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$headers = @{ Authorization = "Basic $base64" }

Next, in PowerShell, if you build the body of the request as a table, like you've shown, don't don't need to wrap the table elements with inverted commas, just leave them as is, but you do need to convert the table to JSON format before submitting it, like this:

$body = @{
 fields = @{
   project = @{
    key = "ProjectKey"
   }
   issuetype = @{
    id = "10705" # Or refer to the Issue type by its name eg. name = "Story"
   }
   summary = "Test"
  }
}
# Convert the body to JSON format
$body = $body | ConvertTo-Json -Depth 50

I'm assuming your $Uri string contains an actual URL to a Jira Server, not the example 'jira.domain.com'

Start with a simple request in the body, like the one I've shown, that contains only the minimum required to create the Issue, which will check your basic code is working before making the request more complex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM