How to create a branch using Bitbucket REST API

snir.tur picture snir.tur · Apr 26, 2017 · Viewed 9k times · Source

How can I create a new branch in Bitbucket repository using REST API?

I'm using Postman client.

Answer

RishiKesh Pathak picture RishiKesh Pathak · Nov 17, 2017

I will show you how to create a branch in Bitbucket using postman and programmatically.

Using Postman

Select method type as POST

Add url: https://example.com/git/rest/api/1.0/projects/{projectKey}/repos/{repoName}/branches

Add Authorization to Basic Auth.

Username and password.

Select Body as raw

Select JSON(application/json)

add this to the body as JSON

{
    "name": "feature/my-feature-branch",
    "startPoint": "refs/heads/master"
}

Click on Send

Now Same programmatically

String authToken = "xyzxyzabcabcabcxyzxyzabcabcabcxyzxyzabcabcabc";

 public boolean createBranchProgrammatically(String projectKey, String repoName, String branchPrefix,String branchName,
            String headStart) {
        Map branches = new HashMap();
        JSONObject json = new JSONObject();
            try {
                String branch = branchPrefix + "/" + branchName;
                json.put("name", branch);
                json.put("startPoint", headStart);
                branches = restTemplate.exchange(myBitbuketUrl + "git/rest/api/1.0/projects/"
                        + projectKey + "repos" + repoName + "/branches",
                        HttpMethod.POST, postRequestEntityForBitbuket(json.toString()), Map.class).getBody();

                break;
            } catch (RestClientException e) {
                logger.error("Branches could not be created from bitbucket for "  , e);            

                return false;
            }

            } 
        return true;
    }



public HttpEntity<String> postRequestEntityForBitbuket(String jsonAsString) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + authToken);
        headers.add("content-type", "application/json");

        return new HttpEntity<String>(jsonAsString, headers) ;
    }