Introduction to GitHub API
The GitHub API offers a wide array of features designed to help developers
interact programmatically with GitHub, making it easier to manage repositories,
issues, pull requests, and more. By leveraging these APIs, developers can automate
routine tasks, integrate GitHub with other applications, and build robust applications
on top of their GitHub workflows.
Getting Started with GitHub API
To use the GitHub API, you need to authenticate using OAuth tokens. Here is a
quick example of how you can authenticate and make a request to list repositories:
curl -H "Authorization: token YOUR_ACCESS_TOKEN" \
https://api.github.com/user/repos
Useful GitHub API Endpoints
Creating a Repository
curl -H "Authorization: token YOUR_ACCESS_TOKEN" \
-d '{"name": "new-repo", "private": true}' \
https://api.github.com/user/repos
Listing Issues
curl -H "Authorization: token YOUR_ACCESS_TOKEN" \
https://api.github.com/repos/USERNAME/REPO/issues
Creating an Issue
curl -H "Authorization: token YOUR_ACCESS_TOKEN" \
-d '{"title": "New Issue", "body": "Issue details"}' \
https://api.github.com/repos/USERNAME/REPO/issues
Listing Pull Requests
curl -H "Authorization: token YOUR_ACCESS_TOKEN" \
https://api.github.com/repos/USERNAME/REPO/pulls
Merging a Pull Request
curl -H "Authorization: token YOUR_ACCESS_TOKEN" \
-d '{"commit_message": "Merging PR"}' \
https://api.github.com/repos/USERNAME/REPO/pulls/PULL_NUMBER/merge
Building an Application with GitHub API
Let’s create a simple command-line application in Python that lists all repositories,
issues, and allows you to create a new issue. Here is a sample script using the
requests
library:
import requests
token = 'YOUR_ACCESS_TOKEN'
headers = {
'Authorization': f'token {token}',
'Accept': 'application/vnd.github.v3+json'
}
def list_repositories():
url = 'https://api.github.com/user/repos'
response = requests.get(url, headers=headers)
repos = response.json()
for repo in repos:
print(repo['name'])
def list_issues(repo):
url = f'https://api.github.com/repos/{repo}/issues'
response = requests.get(url, headers=headers)
issues = response.json()
for issue in issues:
print(f"{issue['title']}: {issue['body']}")
def create_issue(repo, title, body):
url = f'https://api.github.com/repos/{repo}/issues'
issue = {'title': title, 'body': body}
response = requests.post(url, json=issue, headers=headers)
return response.json()
if __name__ == '__main__':
list_repositories()
list_issues('YOUR_REPO_NAME')
create_issue('YOUR_REPO_NAME', 'Issue Title', 'Issue Body')
With this script, you can easily manage your GitHub repositories and handle issues efficiently.
Hash: e0ad62b4ff7147a8ff5adf2e4e0503497c25d8a4de65dc2857dc05645cb3bb4c