Skip to content

Instantly share code, notes, and snippets.

@JeffPaine
Created July 19, 2012 17:24
Show Gist options
  • Save JeffPaine/3145490 to your computer and use it in GitHub Desktop.
Save JeffPaine/3145490 to your computer and use it in GitHub Desktop.
Make an issue on github using API V3 and Python
import json
import requests
# Authentication for user filing issue (must have read/write access to
# repository to add issue to)
USERNAME = 'CHANGEME'
PASSWORD = 'CHANGEME'
# The repository to add this issue to
REPO_OWNER = 'CHANGEME'
REPO_NAME = 'CHANGEME'
def make_github_issue(title, body=None, assignee=None, milestone=None, labels=None):
'''Create an issue on github.com using the given parameters.'''
# Our url to create issues via POST
url = 'https://api.github.com/repos/%s/%s/issues' % (REPO_OWNER, REPO_NAME)
# Create an authenticated session to create the issue
session = requests.session(auth=(USERNAME, PASSWORD))
# Create our issue
issue = {'title': title,
'body': body,
'assignee': assignee,
'milestone': milestone,
'labels': labels}
# Add the issue to our repository
r = session.post(url, json.dumps(issue))
if r.status_code == 201:
print 'Successfully created Issue "%s"' % title
else:
print 'Could not create Issue "%s"' % title
print 'Response:', r.content
make_github_issue('Issue Title', 'Body text', 'assigned_user', 3, ['bug'])
@Vudum
Copy link

Vudum commented Oct 28, 2020

How do I get the bug ID shown immediately in the log when a bug is created? At the moment in the log, we can find "Successfully created Issue "%s"' % title". But how to see the newly created bug ID in the log?

@ADI10HERO
Copy link

Can we "update" issue title using github API? or modifying the above code?
If yes, then can I get an example snippet to do the same?

@hingoman25
Copy link

I tried using @rapekas way of posting issues but was having some trouble. I receive the 202 code which means that the request was successful but for some reason the issue does not show up when I check my account. Has anyone dealt with this?

@DerBla
Copy link

DerBla commented Dec 27, 2021

@ADI10HERO, this is late but, you would need to change the URL to add the issue number and only add the values you want to update in the body. Also, it would be a patch instead of a post request. Docs for reference https://docs.github.com/en/rest/reference/issues#create-an-issue

REPO_OWNER = 'UserName'
REPO_NAME = 'RepoName'
ISSUE_NUMBER= 'IssueNumber'
AUTH_TOKEN= 'PersonalAccessToken'

def update_issue(ISSUE_NUMBER):
    url = 'https://api.github.com/repos/%s/%s/issues/%s' % (
        REPO_OWNER, REPO_NAME, ISSUE_NUMBER)

    # Create an authenticated session to create the issue
    session = requests.Session()
    # Create our issue and headers to authenticate/format
    headers = {'Authorization': 'token %s' % AUTH_TOKEN,
               'Accept': 'application/vnd.github.v3+json'}
    # Put the values you want to modify 
    issue= {
        'title': 'New issue'
        #  'created_at': created_at,
        #  'closed_at': closed_at,
        #  'updated_at': updated_at,
        #  'assignee': assignee,
        #  'milestone': milestone,
        #  'closed': closed
    }

    # Perform the change in your repository
    r = session.patch(url, data=json.dumps(issue), headers=headers)
    if r.status_code == 200:
        print('Successfully changed Issue #{0}: {1}'.format(
            r.json().get("number"), r.json().get("title")))
    else:
        print('Could not modify Issue #{0}'.format(ISSUE_NUMBER))
        print('Response:', r.content)

@ADI10HERO
Copy link

Thanks a lot @DerBla

@Ahmad-Tamim-Hamad
Copy link

How can I create issue in private repository, please help me, thank you.

@luna215
Copy link

luna215 commented Apr 18, 2023

@tamim1992 not sure if you ever got the private repo working, but here is what I did:

import requests
import json


PROJECT_VERSIONS = {
    "molstar": {
        "owner": "molstar",
        "repo": "molstar",
        "custom_repo": "molstar",
        "release": "v3.32.0"
    },
    "indgio": {
        "owner": "epam",
        "repo": "indigo",
        "custom_repo": "Indigo",
        "release": "indigo-1.0.7"
    },
    "ketcher": {
        "owner": "epam",
        "repo": "ketcher",
        "custom_repo": "Ketcher",
        "release": "v2.7.2"
    }
}

RELEASES_URL = "https://api.github.com/repos/{owner}/{repo}/releases"
ISSUE_URL = "https://api.github.com/repos/{owner}/{repo}/issues"
ISSUES_ADD_LABEL = "https://api.github.com/repos/{owner}/{repo}/issues/{issue_id}"
ORGANIZATION = "QuanMol"
TOKEN = "" # This is the PAT token

headers = {
    "Authorization": f"token {TOKEN}",
    "Accept": "application/vnd.github+json"
}

# Create an authenticated session to create the issue
session = requests.Session()
session = requests.Session()
session.auth = ("luna215", TOKEN)

def add_label_to_issue(custom_repo: str, issue_id: str):

    labels = {
        "labels": ["P0 - Critical"]
    }
    session.post(ISSUES_ADD_LABEL.format(owner=ORGANIZATION, repo=custom_repo, issue_id=issue_id), data=json.dumps(labels))
    print(f"Labels added to issue {issue_id}")

def create_update_issue(latest_release: str, current_release: str, custom_repo: str): 
    """Create an issue that describes to update the project"""

    issue = {
        "title": f"Update package to {latest_release}!",
        "body": f"The package is currently using {current_release} and we need to update it to {latest_release}"
    }
    response = session.post(ISSUE_URL.format(owner=ORGANIZATION, repo=custom_repo), data=json.dumps(issue)).json()
    issue_id = response["number"]

    add_label_to_issue(custom_repo, issue_id)

if __name__ == "__main__":

    for project_name, project_info in PROJECT_VERSIONS.items():
        owner = project_info["owner"]
        repo = project_info["repo"]
        custom_repo = project_info["custom_repo"]
        current_release = project_info["release"]

        response = requests.get(RELEASES_URL.format(owner=owner, repo=repo))

        data = response.json()

        latest_release = data[0]["tag_name"]

        if latest_release != current_release:
            # TODO: check if issue exists to update project

            print(f"{project_name} needs to be updated! {current_release} --> {latest_release}")
            create_update_issue(latest_release, current_release, custom_repo)
        

@datatalking
Copy link

I'll test this script this weekend, its got me thinking of ways to improve upon what you did.

  1. Creating a database of choices
  2. Add this code to my data_workbench when I do EDA.

@aN4ksaL4y
Copy link

Hi, Do you have an updated version of it? For example: session = requests.session(auth=(USERNAME, PASSWORD)) is not working with an error: TypeError: session() takes no arguments (1 given)

I changed it to "session = requests.Session(auth=(USERNAME, PASSWORD)) " and still it fails with an error: TypeError: init() got an unexpected keyword argument 'auth'

any help is much appreciated.

try this bud, my latest gist post

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment