You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过API创建Bitbucket Server拉取请求?遇400错误求助

Bitbucket Server API创建PR报400错误的排查与解决

问题分析

你当前的请求存在两个关键问题:

  • JSON请求体格式不符合规范:部分字符串使用了单引号(如'My repo'),而JSON要求所有字符串必须用双引号包裹,这会直接导致服务器解析失败。
  • 冗余字段可能引发冲突:请求体中同时包含state: "OPEN"、open: true、closed: false,Bitbucket API仅需state字段即可,冗余字段可能触发验证逻辑报错。

正确实现步骤

1. 修正请求体格式

使用标准JSON格式,移除冗余字段,示例如下:

{
    "title": "My new PR",
    "description": "This is my new PR.",
    "state": "OPEN",
    "fromRef": {
        "id": "refs/heads/this-is-my-branch",
        "repository": {
            "slug": "my-repo",
            "name": "My repo",
            "project": {
                "key": "KE"
            }
        }
    },
    "toRef": {
        "id": "refs/heads/master",
        "repository": {
            "slug": "my-repo",
            "name": "My repo",
            "project": {
                "key": "KE"
            }
        }
    },
    "locked": false,
    "reviewers": [
        {
            "user": {
                "name": "jeremywat"
            }
        }
    ]
}

2. PowerShell中正确处理JSON

避免手动拼接JSON字符串,建议用PowerShell对象转JSON,确保格式绝对正确:

# 构建请求体对象
$prBody = @{
    title = "My new PR"
    description = "This is my new PR."
    state = "OPEN"
    fromRef = @{
        id = "refs/heads/this-is-my-branch"
        repository = @{
            slug = "my-repo"
            name = "My repo"
            project = @{ key = "KE" }
        }
    }
    toRef = @{
        id = "refs/heads/master"
        repository = @{
            slug = "my-repo"
            name = "My repo"
            project = @{ key = "KE" }
        }
    }
    locked = $false
    reviewers = @(
        @{ user = @{ name = "jeremywat" } }
    )
}

# 序列化为标准JSON
$JsonBody = $prBody | ConvertTo-Json -Depth 10

# 发送请求
Invoke-RestMethod -Headers @{Authorization = "Basic $BasicAuth"} -Body $JsonBody -ContentType 'application/json' -Method POST -Uri "https://my-bitbucket-server.com/rest/api/1.0/projects/KE/repos/my-repo/pull-requests"

3. 额外排查点

  • 确认分支this-is-my-branch存在且有提交,与master分支有差异(无差异的分支无法创建PR)。
  • 检查 reviewer 的用户名jeremywat是否为Bitbucket Server中存在的有效用户名。
  • 若仍报错,添加-ErrorAction Stop并捕获错误详情,查看服务器返回的具体错误信息:
try {
    Invoke-RestMethod -Headers @{Authorization = "Basic $BasicAuth"} -Body $JsonBody -ContentType 'application/json' -Method POST -Uri "https://my-bitbucket-server.com/rest/api/1.0/projects/KE/repos/my-repo/pull-requests" -ErrorAction Stop
} catch {
    Write-Host "错误详情: $($_.Exception.Response.StatusCode.value__)"
    Write-Host "服务器返回内容: $($_.ErrorDetails.Message)"
}

内容的提问来源于stack exchange,提问作者jeremywat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:06:09