How to create a tag for a specific commit in git using git API

1.2k views Asked by At

I have the commit ID in git and would like to create a tag in git for that specific commit in that repo using git rest APIs. I can't clone the repo locally to do this. Need to use the git Rest API's to perform the tag activity.

I tried to use the below API: https://github.xxx.com/api/v3/repos/sample_org/testrepo1/git/tags{/sha}

payload used: {'tag': 'release_2018-02-09-135370b-123-testing','message': 'Testing tagging code','object': sha,'type': 'commit'}

When this call is executed I see it returning 201 success. But when I got to the Git UI I can't find the tag. Is their something I am missing.

Reference API doc URL: https://developer.github.com/v3/git/tags/

1

There are 1 answers

0
Sudarshan On

We can use the release API and get the tag created in the GIT using the REST API. Code snippet as below:

1) First from the short commit ID we need to get the complete 40 character git commit ID for this we can use the below REST API:

repo_url= "https://github.com/api/v3/repos/TestOrg/sampleRepo/commits/short_commit_id"

repo_list = requests.get(repo_url, headers=headers)

data_dict = json.loads(repo_list.text)
sha = data_dict['sha']

In the SHA we will get the 40 character commit id.

2) You can create a Tag object if you need using the below REST API

tag_url = "https://github.com/api/v3/repos/TestOrg/sampleRepo/git/tags"

data_dict = {'tag': 'release_2018-02-09-535370b-123-testing',
             'message': 'Testing tagging code','object': sha,'type': 'commit'}
repo_list = requests.post(tag_url, headers=headers, json=data_dict)

This will create a Tag object. But this will not make it available in the GIT.

3) Now you can use the release REST API and get the release created and that intern will create a tag in the GIT.

release_url = "https://github.com/api/v3/repos/TestOrg/sampleRepo/releases"

data_dict = {"tag_name": "release_2018-02-09-535370b-123-testing", "target_commitish": sha,"name": "release_2018-02-09-535370b-123-testing", "body": "Testing tagging code","draft": False, "prerelease": False}

repo_list = requests.post(release_url, headers=headers, json=data_dict)

With this we can get the release create along with Tag in GIT.