Search code examples
bitbucketbitbucket-apibitbucket-cloud

How to find the default branch of Repository - Bitbucket Cloud API


I went through the complete API documentation of The Bitbucket Cloud Rest API:

https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-group-repositories

But I did not found any way or API to get the default branch of Bitbucket Cloud Repository.

Could anyone help me with this

Thanks


Solution

  • The REST API has a filter for all branches of a repository, its response has a property named isDefault

    curl -s -u $BITBUCKET_KEY $BITBUCKET_URL/rest/api/latest/projects/$PROJECT/repos/$REPO/branches?limit=100 | jq -r '.values[]'
    
    {
      "id": "refs/heads/master",
      "displayId": "master",
      "type": "BRANCH",
      "latestCommit": "c2a944ba03ea7c1ab07b3159660c69647229704e",
      "latestChangeset": "c2a944ba03ea7c1ab07b3159660c69647229704e",
      "isDefault": true
    }
    {
      "id": "refs/heads/release/1.3.5",
      "displayId": "release/1.3.5",
      "type": "BRANCH",
      "latestCommit": "a835d28c8f828610fcc4f0f463b99c4a75039aef",
      "latestChangeset": "a835d28c8f828610fcc4f0f463b99c4a75039aef",
      "isDefault": false
    }
    
    

    A listing can be shown with:

    #!/bin/bash
    # Get branches in a BitBucket repo
    set -euo pipefail
    
    REPO=$1
    PROJECT='MYTEAM'
    
    ## url of  branches in a repo
    BITBUCKET_URL="https://bitbucket.example.com/rest/api/latest/projects/$PROJECT/repos/$REPO/branches?limit=100"
    
    # Check BITBUCKET_URL with a http HEAD request
    OUT=$(curl --fail --head -u "$BITBUCKET_KEY" "$BITBUCKET_URL" 2>&1)
    if [ $? -ne 0 ] ; then
       echo "Error: $OUT"| tail -1
       exit $?
    fi
    
    # Query the JSON output of the request
    JSON=$(curl -s -u "$BITBUCKET_KEY" "$BITBUCKET_URL" 2>&1)
    echo "$JSON" | jq -r '.values[] | .displayId'
    

    https://developer.atlassian.com/cloud/bitbucket/rest/intro/#filtering