I was working around a few days back, managing the release of the project with versioning and proper tags associated with it which results in writing the python code.
I have written a simple python function that will call the API of GitHub and will Create/Fetch /Delete the release on GitHub.
Note** You can manage the same with CURL command too but I was facing some authentication issue, so haven’t done, I haven’t tried with explicitly passing the auth token in header by -H tag, you can give a try.
Have a look at the below snippet of code which can be easily integrated with Jenkins pipeline
import requests
import json
user = "" #username of github account
repo = "" #repository_name
auth = "" #authentication token
url = "https://api.github.com"
header = {"Authorization": "token %s" %(auth), 'Accept': 'application/vnd.github.v3.raw'}
tag_name = "" #tag_name of release
releaseId = "" #releaseID
Here, tag_name and releaseId
variables are only required if you want to delete a particular release, which you will rarely come across.
# Fetch latest release from github
def latestRelease():
try:
releases = requests.get('%s/repos/%s/%s/releases/latest' %(url,user,repo), headers=header).json()
print(releases['tag_name'], releases['id'])
except:
print('Release Not Found')
The above code will be used to fetch the latest release present on GitHub.
# Create latest release on github
def postNewrelease():
try:
with open('release.json') as newRelease:
_release = json.load(newRelease)
release_new = requests.post('%s/repos/%s/%s/releases' %(url,user,repo), json=_release, headers=header).json()
print(release_new)
except:
print("error while creating new release")
This snippet of code is used to create the release on GitHub, which contains payload
in JSON format.
release.json
will look something like below,
{
"tag_name": "v1.6.0",
"target_commitish": "master",
"name": "v1.6.0",
"body": "nikhil python api call release",
"draft": false,
"prerelease": false
}
Even with this payload, you can easily create prerelease of the master branch, which can be tested in the Staging environment.
# Delete release from github by passing tag_name & releaseId
def deleterelease():
try:
releaseDeleteTag = requests.delete('%s/repos/%s/%s/git/refs/tags/%s' %(url,user,repo,tag_name), headers=header)
releaseDeleteId = requests.delete('%s/repos/%s/%s/releases/%s' %(url,user,repo,releaseId), headers=header)
print(releaseDeleteId,releaseDeleteTag)
except:
print("error wile deleting release")
The above deletion method is not often required.
The full script is available in the below repository.
Github Link: https://github.com/nik0811/github-release-api.git
Feel free to comment below, if you will found any mistakes or required any type of modifications/enhancement. The code is fully tested so hopefully, you will not find any issues.
Top comments (0)