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

使用Bitbucket REST API创建新文件失败的技术求助

解决Bitbucket Server API创建新文件的问题
  • 正确的URL格式:必须包含完整的目标文件路径(即便文件尚未存在),正确结构为:
    http://{baseurl}/rest/api/latest/projects/{projectKey}/repos/{repositorySlug}/browse/{filePath}
    比如要在config目录下创建new-file.yml,路径就写config/new-file.yml,不能只停留在仓库根目录或仅添加文件名。

  • 必填参数要点:

    • 留空sourceCommitId是正确操作,但必须明确指定branch参数(如main、master)——这是文档没重点强调但创建新文件时的必填项。
    • 请求体需包含content(你的YML字符串内容)、message(提交说明),以及branch字段。
  • 错误原因拆解:

    • 405错误是因为使用了错误的端点,PUT请求必须指向具体的文件路径(即使文件不存在),不能只到仓库或/browse层级。
    • 404提示“文件已被删除”,大概率是分支参数不正确,或是文件路径格式有误(比如斜杠使用错误、大小写不匹配)。
  • 示例JavaScript请求代码:

    async function createBitbucketFile(baseUrl, projectKey, repoSlug, filePath, content, branch, commitMessage, auth) {
      const url = `${baseUrl}/rest/api/latest/projects/${projectKey}/repos/${repoSlug}/browse/${filePath}`;
      
      const response = await fetch(url, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Basic ${btoa(auth.username + ':' + auth.password)}`
        },
        body: JSON.stringify({
          content: content,
          message: commitMessage,
          branch: branch,
          sourceCommitId: '' // 留空用于创建新文件
        })
      });
    
      if (!response.ok) {
        const errorDetails = await response.json();
        throw new Error(`API请求失败: ${response.status} - ${errorDetails.message}`);
      }
    
      return await response.json();
    }
    
    // 使用示例
    createBitbucketFile(
      'http://your-bitbucket-server',
      'PROJ',
      'your-repo',
      'config/new-config.yml',
      'your-yml-content-string',
      'main',
      'Add new config file',
      { username: 'your-user', password: 'your-token-or-password' }
    )
    .then(result => console.log('文件创建成功:', result))
    .catch(err => console.error('错误:', err));
    
  • 额外注意事项:

    • 确保账号对目标仓库拥有写入权限,否则会返回403错误。
    • 文件路径含特殊字符时需做URL编码(比如空格替换为%20)。
    • 若目标分支是受保护分支,需确认账号有权限在该分支提交,或改用非保护分支操作。

内容的提问来源于stack exchange,提问作者B. Allred

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:02:20