61

Seems like it's missing from the "Repos" docs for v1, v2, and v3...how do I create a branch using the Github API?

  • Sorry about that, I realized you wanted to branch a repo after I posted my answer. – Marvin Pinto Feb 29 '12 at 20:59
  • I'm trying to integrate into this into a managent application; just assumed I could use the API to manage Github projects. –  Feb 29 '12 at 22:36

4 Answers4

101

The V3 API mentions branches in its reference page

The ref in the URL must be formatted as heads/branch, not just branch.
For example, the call to get the data for a branch named sc/featureA would be:

GET /repos/:user/:repo/git/refs/heads/sc/featureA

Create a Reference

POST /repos/:user/:repo/git/refs

Parameters

ref

String of the name of the fully qualified reference (ie: refs/heads/master). If it doesn’t start with ‘refs’ and have at least two slashes, it will be rejected.

sha

String of the SHA1 value to set this reference to

So it should be possible to create a new branch, by naming a new '/heads' in the ref parameter.


Potherca points out to a working test, using the service of www.hurl.it (which makes HTTP requests)

  • Find the revision you want to branch from.
    Either on Github itself or by doing a GET request from Hurl:

    https://api.github.com/repos/<AUTHOR>/<REPO>/git/refs/heads

  • Copy the revision hash

  • Do a POST request from Hurl to https://api.github.com/repos/<AUTHOR>/<REPO>/git/refs with the following as the POST body :

      {
          "ref": "refs/heads/<NEW-BRANCH-NAME>",
          "sha": "<HASH-TO-BRANCH-FROM>"
      }
    

    (obviously replacing the <NEW-BRANCH-NAME> with the name your want the new branch to have and the <HASH-TO-BRANCH-FROM> with, you know, the hash of the revision you want to branch from)

    You will need to use HTTP basic and fill in your Github credentials to access the Github API.

  • Press the Send button and your branch will be created!


In 2022, you can also use gh api

gh api \
  --method POST \
  -H "Accept: application/vnd.github.v3+json" \
  /repos/OWNER/REPO/git/refs \
  -f ref='refs/heads/featureA'
 -f sha='aa218f56b14c9653891f9e74264a383fa43fefbd'
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 9
    Ahhh. References, what a place to put it. Thanks! –  Mar 01 '12 at 22:45
  • 1
    I tried this out (using [hurl.it](http://hurl.it/)). Using a branch name for a ref (don't forget to put `refs/heads/` in front of it) and the hash of the commit to branch from as the sha. POSTed it and I got a 201 'Created' response. So... **I can verify this works!** – Potherca Oct 05 '12 at 14:25
  • 2
    [Here is a gist with a complete write-up of how to do this](https://gist.github.com/potherca/3964930) – Potherca May 03 '13 at 18:14
  • @Potherca great! I reference your gist in the answer for more visibility. – VonC May 03 '13 at 18:20
  • 1
    @VonC Cool! I hope you don't mind, I edited your addition to be one solid blockquote. – Potherca May 03 '13 at 18:40
  • Python implementation https://github.com/PyGithub/PyGithub/blob/74cd6856de404dc3109360860b712d62458c24eb/github/Repository.py#L906-L924 – crizCraig Sep 03 '19 at 20:18
  • @VonC any idea about how to do this if the repo is in an organization? – Aditya Mar 31 '20 at 00:00
  • 1
    @Aditya For creating a branch, it should be the same (unless the branch API has evolved since I wrote this 8 years ago) – VonC Mar 31 '20 at 04:22
6

Adding to @VonC answer, here is working snippet in python.

import requests
headers = {'Authorization': "Token " + 'YOUR_TOKEN_HERE'}
url = "https://api.github.com/repos/<USERNAME>/<REPO>/git/refs/heads"
branches = requests.get(url, headers=headers).json()
branch, sha = branches[-1]['ref'], branches[-1]['object']['sha']
res = requests.post('https://api.github.com/repos/<USERNAME>/<REPO>/git/refs', json={
    "ref": "refs/heads/newbranch",
    "sha": sha
}, headers=headers)
print(res.content)
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
5

This is a common problem for all the students when we create API for creating a branch in GitHub

{
  "message": "Not Found",
  "documentation_url": "https://developer.github.com/v3"
}

For solving this error during create repository in Github.....

  1. First create a personal token in

    Github=>setting=>developerOption=>generatePersonalToken...

                     or 
    

    during gitLogin bu Oauth when you pass client_id that time you pass scope=repo(Because it's allow all the Repository when you used token or anything)

  2. After that: hit the API(get)

    https://api.github.com/repos/<your login name>/<Your Repository Name>/git/refs/heads

  3. You got a response which is like

    Response => {
    [
    {
        "ref": "refs/heads/<already present branch name for ref>",
        "node_id": "jkdhoOIHOO65464edg66464GNLNLnlnnlnlna==",
        "url": " https://api.github.com/repos/<your login name>/<Your Repository Name>/git/refs/heads/<already present branch name for ref>",
        "object": {
            "sha": "guDSGss85s1KBih546465kkbNNKKbkSGyjes56",
            "type": "commit",
            "url": " https://api.github.com/repos/<your login name>/<Your Repository Name>/git/commits/guDSGss85s1KBih546465kkbNNKKbkSGyjes56"
        }
    }
    ]
    }
    
  4. Complete this process again hit API (Post)

    https://api.github.com/repos/Bhupi2508/Test/git/refs...
    

    And send data in JSON format like this:

    {
        "ref": "refs/heads/<new branch name>",
        "sha": "4661616ikgohlKIKHBK4634GRGSD66"
    }
    

    THEN YOU CREATE A BRANCH IN GITHUB By APIs

    And the process for Delete Branch hit only DELETE (first) APIs

4

Struggled to do this for Private repos thus answering the question for same cases:

For private repos you need to have the requests authenticated via "username" & "password" or OAUTH. Steps below;

  1. Find the Personal access token for your account in github developer settings.

  2. Make an authenticated GET request with base branch name.

  3. From the response of GET request filter the commit SHA using jq.

  4. Post the new branch name and commit SHA as body in POST request to github.

In Action:

TOKEN=<GITHUB-AUTH-TOKEN-VALUE>
Previous_branch_name=ABC
New_branch_name=XYZ

SHA=$(curl -H "Authorization: token $TOKEN" https://api.github.com/repos/<REPO>/git/refs/heads/$Previous_branch_name | jq -r '.object.sha')

curl -X POST -H "Authorization: token $TOKEN" \
-d  "{\"ref\": \"refs/heads/$New_branch_name\",\"sha\": \"$SHA\"}"  https://api.github.com/repos/<REPO>/git/refs
tostao
  • 2,803
  • 4
  • 38
  • 61
  • your code looks good am trying to acheive the same could you please explain your code in detail please? When i execute the code it throws an error as mentioned below: Note: i am able to fetch the SHA value. 400 Bad Request

    Bad Request

    Your browser sent a request that this server could not understand.

    curl: (56) Recv failure: Connection reset by peer
    – Docgyan Aug 26 '20 at 08:06
  • Assuming that you are making the request from shell or some tool (like postman etc) to process same. If you are getting 400 bad request, please check the URL in POST request. To create a branch you need to provide the new branch name & old branch's SHA in data in POST request. – Gaurav Dalal Sep 15 '20 at 16:31