通过PowerShell使用REST API创建JIRA问题

时间:2019-05-02 08:13:22

标签: powershell jira-rest-api

我正在尝试通过Powershell创建JIRA问题。

这是我的代码。

function ConvertTo-Base64($string) {
$bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
$encoded = [System.Convert]::ToBase64String($bytes);
return $encoded;
}

function Get-HttpBasicHeader([string]$username, [string]$password, $Headers = @{}) {
    $b64 = ConvertTo-Base64 "$($username):$($Password)"
    $Headers["Authorization"] = "Basic $b64"
    $Headers["X-Atlassian-Token"] = "nocheck"
    return $Headers
}

$restapiuri = "https://baseurl/rest/api/2/issue/"
$headers = Get-HttpBasicHeader "user" "password"

$body = ('
{
    "fields":
    {
        "project":
        {
            "id": "10402"
        },

        "summary": "Test",

        "description": "Test",

        "duedate": "2019-05-11",

        "issuetype":
        {
            "id": "3"
        },

        "reporter":
        {
            "name": "user"
        },

        "priority":
        {
            "id": "10101"
        },

        "customfield_11403": "Test",

        "security":
        {
            "id": "11213"
        },

        "components":
        [
            {           
                "id": "10805"
            }
        ]
    }
}')

Invoke-RestMethod -uri $restapiuri -Headers $headers -Method POST -ContentType "application/json" -Body $body

它的JSON部分运行正常,因为我已经使用Postman进行了尝试,并且问题已创建。

但是在Powershell中,我总是收到一个400错误的请求。有谁知道为什么会这样?

谢谢!

编辑:根据答案编写代码示例

$body = @{

    "fields" = @{

        "project" = @{

            "id" = "10402";
        }

        "summary" = "Test";

        "description" = "Test";

        "duedate" = "2019-05-11";

        "issuetype" = @{

            "id" = "3";
        }

        "reporter" = @{

            "name" = "user";
        }

        "priority" = @{

            "id" = "10101";
        }

        "customfield_11403" = "Test";

        "security" = @{

            "id" = "11213";
        }
    }
}

2 个答案:

答案 0 :(得分:0)

使用Invoke-RestMethod来使用REST-API。将JSON保存为字符串并将其用作正文, 例如:

$body = @'
{
    "fields":
    {
        "project":
        {
            "id": "10402"
        },

        "summary": "Test",

        "description": "Test",

        "duedate": "2019-05-11",

        "issuetype":
        {
            "id": "3"
        },

        "reporter":
        {
            "name": "user"
        },

        "priority":
        {
            "id": "10101"
        },

        "customfield_11403": "Test",

        "security":
        {
            "id": "11213"
        },

        "components":
        [
            {           
                "id": "10805"
            }
        ]
    }
}
'@

Invoke-RestMethod -uri $restapiuri -Headers $headers -Method POST -ContentType "application/json" -Body $body

答案 1 :(得分:0)

问题出在这里。

$ restapiuri =“ https://baseurl/rest/api/2/issue/

应该是

$ restapiuri =“ https://baseurl/rest/api/2/issue

此更改之后,它终于起作用了!额外的/是PowerShell似乎不喜欢的东西:)