10

I'm looking for an Azure DevOps Rest API to create a new branch from an existing branch.

irudne
  • 189
  • 1
  • 2
  • 8

5 Answers5

13

Azure DevOps Rest API to create a branch from a specific branch

Konteks pointed out the correct REST API.

We could use the Initial commit (Create a new branch) to create a branch, but if you want to create a branch from a specific branch, we need modify the Request Body.

POST https://dev.azure.com/fabrikam/_apis/git/repositories/{repositoryId}/pushes?api-version=5.1

First, we need use the REST API Repositories - List to get the repositoryId.

GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=4.1

Then, use the REST API Refs - List with filter=<BranchName> to get the oldObjectId for your specific branch:

GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/refs?filter=heads/master&api-version=5.1

Now, we could use the REST API Repositories - List with following request body to create a new branch from a specific branch:

{
  "refUpdates": [
    {
      "name": "refs/heads/<DefineYourNewBranchName>",
      "oldObjectId": "<oldObjectId we get from above REST API>"
    }
  ],
  "commits": [
    {
      "comment": "Initial commit.",
      "changes": [
        {
          "changeType": "add",
          "item": {
            "path": "/readme111.md"
          },
          "newContent": {
            "content": "My first file!",
            "contentType": "rawtext"
          }
        }
      ]
    }
  ]
}

Result from postman:

enter image description here

This is my test powershell scripts:

$connectionToken="<PAT Here>"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))

$headers = @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }

$url= "https://dev.azure.com/<Organizationname>/<ProjectName>/_apis/git/repositories/<repositoryId>/pushes?api-version=5.1"


$body =@"
{
  "refUpdates": [
    {
      "name": "refs/heads/Test228",
      "oldObjectId": "a57f0c34f8ec7330bdc37e7631f7be3cc3ea3956"
    }
  ],
  "commits": [
    {
      "comment": "Initial commit.",
      "changes": [
        {
          "changeType": "add",
          "item": {
            "path": "/readme111.md"
          },
          "newContent": {
            "content": "My first file!",
            "contentType": "rawtext"
          }
        }
      ]
    }
  ]
}
"@


Write-Host "$url"
$response= Invoke-RestMethod -Uri $url -ContentType "application/json-patch+json" -Body $body -headers @{authorization = "Basic $base64AuthInfo"} -Method POST

Hope this helps.

Leo Liu
  • 71,098
  • 10
  • 114
  • 135
  • 1
    What if I just want a new branch? Not to add or change a file, just a new branch? Can I simply leave out the 'commit' section of the Request json? – Tom Padilla Jun 25 '20 at 12:00
  • 1
    @TomPadilla, I needed to do this as well. If you want to just simply create a new branch from another branch, do all the steps that Leo provided, but in the last step for your POST, following the request body from the example [from here](https://learn.microsoft.com/en-us/rest/api/azure/devops/git/refs/update%20refs?view=azure-devops-rest-5.1#examples). Also remember to use the `repositoryId` you got from the second step for the `newObjectId` in the example from the link. I.e. The `newObjectId` represents the source branch reference you got from the second step – Eric Chhun Jul 14 '20 at 15:11
  • Thank you. Exactly what I needed to know. – Tom Padilla Jul 29 '20 at 11:54
  • What if I want to create a branch from another branch but not latest commit, but a specific previous one? – Alejandro Galera Jul 28 '22 at 07:31
9

I captured the requests created by the AzureDevOps web UI and found out that creating a branch from a specific branch is quite simple task for the REST api.

$repository = "repositoryName"
$newBranch = "newBranchName"
$baseBranch = "baseBranchName"

$organization = "organizationName"
$project = "projectName"
$pat = "personalAccessToken"

$base64AuthInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$pat"))

$headers = @{ Authorization = "Basic $base64AuthInfo" }

# Get ID of the base branch
$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?filter=heads/$baseBranch&api-version=5.1"
$baseBranchResponse = Invoke-RestMethod -Uri $url -ContentType "application/json" -headers $headers -Method GET

# Create a new branch
$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?api-version=5.1"
$body = ConvertTo-Json @(
@{
    name = "refs/heads/$newBranch"
    newObjectId = $baseBranchResponse.value.objectId
    oldObjectId = "0000000000000000000000000000000000000000"
})

$response = Invoke-RestMethod -Uri $url -ContentType "application/json" -Body $body -headers $headers -Method POST
  • Great solution! A few tips from when I used this. To specify the base branch as the master branch it was enough with just writing "master", ie. no need for the full name "refs/heads/master" (which seems to be used behind the scenes). And regarding the PAT token, you will need the Read&Write Code permission to be allowed to create branches. – Fhyarnir Jul 02 '21 at 07:25
  • Hi, Is there any way we can add commit date to create a branch from master? I need to create a branch from master using last commit of particular date. As of now, I'm using this syntax to get the date. but dont know how to create branch based on that date $url="https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/commits?searchCriteria.toDate=$toDate&api-version=6.0" Thanks in Advance – Kart Jul 14 '21 at 14:11
  • 1
    I'm not sure if I understand your request correctly. But if you want to create a new branch at a specified commit you can use the "commits" endpoint to get your commit id and use it when creating the new branch. Something like this `$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/commits?searchCriteria.fromDate=07/15/2021&api-version=5.1"` `$commitsResponse = Invoke-RestMethod -Uri $url -ContentType "application/json" -headers $headers -Method GET` and then `newObjectId = $commitsResponse.value[0].commitId` – Miroslav Ježík Jul 15 '21 at 15:46
  • i need to create a branch from last commit of specified date. For this, i have collected the commit id based on date. Here are my commands. $url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/commits?searchCriteria.toDate=$toDate&api-version=6.0" $response = Invoke-RestMethod -Uri $url -Method GET -headers $headers $output = $response.value | Select -First 1 $commitid = $output.commitid Till here, im getting commit id of that specified date. Now, im struck at creating branch from that commit id. Could you please help me here? – Kart Jul 15 '21 at 19:01
  • 1
    Finally, I have created the branch from commit id `$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/refs?api-version=6.0" $body = ConvertTo-Json @( @{ name = "refs/heads/$newBranch" newObjectId = $output.commitid oldObjectId = "0000000000000000000000000000000000000000" }) $response = Invoke-RestMethod -Uri $url -Method POST` Thank you @Miroslav Ježík for your kind response – Kart Jul 16 '21 at 01:40
1

This worked for me:

To create/update/delete: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/refs/update%20refs?view=azure-devops-rest-5.0#create/update/delete-a-ref-by-repositoryid

To get objectId: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/refs/list?view=azure-devops-rest-5.0#refs

Naga Raja
  • 11
  • 1
  • How? How, on earth, did you make heads or tails of that rambling mess? There isn't a 'create' or 'add' on the entire page (except the title). They give an example, but it's... What...? A random example of all three actions at the same time? In all honesty - how am I supposed to read that page and come away with the code posted above by Leo Liu-MSFT? – Tom Padilla Jun 25 '20 at 11:57
  • Upvoting because it reports link to officicial doc in Microsoft. Sad that it is not better documented there. – Andry Aug 15 '21 at 14:47
0

Sparrow plugin does what you need ( using Rest API ):

s6 --plg-run ado-git-branch-create@project=Backends,repo=Catalog,branch_from=dev,branch=feature

Please pay attention, it does not create any dummy files for that, it only references for an existing branch through it's internal object ID.

Feel free to still the code ;-)).


PS Disclosure. I am the tool author, more details could be found here - https://github.com/melezhik/Spazure

Alexey Melezhik
  • 962
  • 9
  • 27