首页 > 解决方案 > 用于拉取请求的 AzureDevops Api 调用不起作用

问题描述

我指的是这个页面,通过 API 调用在 Azure DevOps 的构建过程中创建一个拉取请求。我正在使用授权Bearer$(System.AccessToken)不是 PAT 凭据。在我之前的步骤中,我使用Bearerwith$(System.AccessToken)来获得buildNumber无缝工作的 via API 调用。但是,如果我在下面的任务中使用相同的POST机制来创建拉取请求,它就不起作用并给我 400 错误代码。

任何人都可以向我建议,我怎样才能使这项工作?

          - task: Bash@3
            inputs:
              targetType: 'inline'
              script: |
                
                
                echo 'Started createing pull-request'
                url="https://dev.azure.com/{Organization name}/{Project name}/_apis/git/repositories/$(Build.Repository.ID)/pullrequests?api-version=6.0"
                echo $url
                ret=$(curl -d '{"sourceRefName": $(BUILD.SOURCEBRANCH), "targetRefName": "refs/heads/devlopment", "title": "test",  "description": "test" }' -X POST -H "Authorization:Bearer $(System.AccessToken)" -H "Content-Type:application/json"  ${url} --write-out "%{http_code}" --output response.json)
                echo $ret
                cat response.json

标签: azure-devopsazure-pipelines

解决方案


错误在 JSON 中。修复并重新格式化 JSON 现在都可以正常工作了。这是现在的任务,添加了一些额外的内容:标题和描述已参数化。

- task: Bash@3
            displayName: Creating Pull request 
            inputs:
              targetType: 'inline'
              script: |
                url="$(System.TeamFoundationCollectionUri)/$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.ID)/pullrequests?api-version=6.0"
                ret=$(curl -X POST \
                --silent \
                -H "Authorization:Bearer $(System.AccessToken)"  \
                -H "Content-Type:application/json" \
                ${url} \
                --write-out "%{http_code}" \
                --output response.json \
                -d'{
                  "sourceRefName":"$(BUILD.SOURCEBRANCH)",
                  "targetRefName":"refs/heads/<branch-name>",
                  "title":"$(Title)",
                  "description":"$(Description)"
                  }' )
                if [[ $ret -ne 201 ]];
                then
                  message=$(cat response.json | jq '.message' --raw-output)
                  echo "##vso[task.logissue type=error;] ERROR MESSAGE: ${message}"
                  exit 1
                fi
            continueOnError: false

推荐阅读