my-notes

GitHub_API

1 min read

GitHub API

Interact with GitHub programmatically.


πŸ”§ Using gh CLI

REST API Call

gh api repos/{owner}/{repo}

Gets repository info.


Get User Info

gh api user

Gets authenticated user info.


POST Request

gh api repos/{owner}/{repo}/issues -X POST -f title="Bug" -f body="Description"

Creates an issue.


With JSON Body

gh api repos/{owner}/{repo}/labels -X POST \
  --input - <<< '{"name":"urgent","color":"ff0000"}'

Creates label with JSON body.


πŸ”· GraphQL

Basic Query

gh api graphql -f query='{ viewer { login } }'

Gets your username.


Get Repository Info

gh api graphql -f query='
  query {
    repository(owner: "owner", name: "repo") {
      name
      description
      stargazerCount
    }
  }
'

Gets repository details.


With Variables

gh api graphql -f query='
  query($owner: String!, $name: String!) {
    repository(owner: $owner, name: $name) {
      name
    }
  }
' -f owner="octocat" -f name="Hello-World"

Uses query variables.


🐍 Python

Install PyGithub

pip install PyGithub

Install GitHub library.


Python Example

from github import Github

g = Github("YOUR_TOKEN")
repo = g.get_repo("owner/repo")

# List issues
for issue in repo.get_issues():
    print(issue.title)

# Create issue
repo.create_issue(title="Bug", body="Description")

Python GitHub API usage.


πŸ“¦ JavaScript

Install Octokit

npm install @octokit/rest

Install Octokit.


JavaScript Example

import { Octokit } from "@octokit/rest";

const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });

// Get repo
const { data: repo } = await octokit.repos.get({
  owner: "owner",
  repo: "repo",
});

// Create issue
await octokit.issues.create({
  owner: "owner",
  repo: "repo",
  title: "Bug",
  body: "Description",
});

JavaScript API usage.


πŸ” Authentication

Personal Access Token

  1. Go to Settings β†’ Developer settings
  2. Personal access tokens β†’ Tokens (classic)
  3. Generate new token with needed scopes

Use Token with gh

gh auth login --with-token < token.txt

Authenticates with token.


πŸ’‘ Tips

Rate Limits

REST: 5000 req/hour GraphQL: 5000 points/hour

Pagination
gh api repos/{owner}/{repo}/issues --paginate


#github #api #rest #graphql

Built with mdgarden