Code 11: Using Github API via Python

Learn to update an Issue Description with Github’s API
github
api
python
Author

Tony Phung

Published

October 1, 2024

1. Install and load libraries

!pip install python-dotenv
!pip install requests
Requirement already satisfied: python-dotenv in /home/tonydevs/.local/share/virtualenvs/og_files-6Eyjdxah/lib/python3.10/site-packages (1.0.1)
Requirement already satisfied: requests in /home/tonydevs/.local/share/virtualenvs/og_files-6Eyjdxah/lib/python3.10/site-packages (2.32.3)
Requirement already satisfied: charset-normalizer<4,>=2 in /home/tonydevs/.local/share/virtualenvs/og_files-6Eyjdxah/lib/python3.10/site-packages (from requests) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /home/tonydevs/.local/share/virtualenvs/og_files-6Eyjdxah/lib/python3.10/site-packages (from requests) (3.10)
Requirement already satisfied: urllib3<3,>=1.21.1 in /home/tonydevs/.local/share/virtualenvs/og_files-6Eyjdxah/lib/python3.10/site-packages (from requests) (2.2.3)
Requirement already satisfied: certifi>=2017.4.17 in /home/tonydevs/.local/share/virtualenvs/og_files-6Eyjdxah/lib/python3.10/site-packages (from requests) (2024.8.30)
import os, requests
from dotenv import load_dotenv, find_dotenv

2. Setup Github Personal Token

  • https://github.com/settings/tokens -> Developer Setings
  • Personal access tokens -> Tokens (classic)
  • Generate new token

3. Create .env file and set token to parameter

if find_dotenv():
    print(f"Using .env file: {find_dotenv()}")
    load_dotenv()
else:
    print("Error: .env not found, Place in cwd or use load_dotenv('/path/to/your/.env')")
Using .env file: /home/tonydevs/blog/.env

4. Use Github API

4.1 Create Task List and Set List Action parameter

# 1. Choose 'New' or 'Append' to current description:
list_action_param = 'New'
# list_action_param = 'Append'

# 2. Enter list of tasks
list_of_tasks = [
  "A very cool new task",
  "Another mad chill new task",
  "A final exquisite crazy new task"
]

4.2 Set Github Configs

# 3. Set Repo and Issue
REPO_USER = "tonyjustdevs"
REPO_TOPIC = "blog"
ISSUE_NUMBER = 95

# 4. Configs
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
REPO = f"{REPO_USER}/{REPO_TOPIC}"
GITHUB_API_URL = f"https://api.github.com/repos/{REPO}/issues"
HEADERS = {
    "Authorization": f"Bearer {GITHUB_TOKEN}",
    "Accept": "application/vnd.github.v3+json"
}

4.3 Check Response is OKAY (200)

issue_url = f"{GITHUB_API_URL}/{ISSUE_NUMBER}"
response = requests.get(issue_url, headers=HEADERS) #200
response
<Response [200]>

4.4 Get and Check Current Description Data

issue_data = response.json()
description = issue_data['body']
description
'sample description'

4.5 Prepare description string objects

print(f"List action parameter selected: '{list_action_param}'")
if description is not None and list_action_param=="Append": #"New" or "Append"
  print("Description exists, no action required.")
else:
  description= ""
  print("New (empty) description created.") 
List action parameter selected: 'New'
New (empty) description created.

4.6 Convert tasks to single string object

added_description_str = ""
EOL_str = "\r\n"
github_check_pointer_str = "- [ ]"
for task in list_of_tasks:
  added_description_str += f"{github_check_pointer_str} {task}{EOL_str}"
  print(f"'{task}' appended.")
'A very cool new task' appended.
'Another mad chill new task' appended.
'A final exquisite crazy new task' appended.
added_description_str
'- [ ] A very cool new task\r\n- [ ] Another mad chill new task\r\n- [ ] A final exquisite crazy new task\r\n'

4.7 Append to current description

description+=added_description_str
end_description_str = "description added via [tony_add_tasks.ipynb]"
description += f"{EOL_str}{end_description_str}{EOL_str}"
print(description)
- [ ] A very cool new task
- [ ] Another mad chill new task
- [ ] A final exquisite crazy new task

description added via [tony_add_tasks.ipynb]

4.7 Prepare description dictionary object to send to API

update_data = {
    "body": description
}

4.8 Update description object via API

response = requests.patch(issue_url, headers=HEADERS, json=update_data)

if response.status_code == 200:
    print("Issue description updated successfully!")
else:
    print(f"Failed to update issue description: {response.status_code}, {response.text}")
Issue description updated successfully!