Skip to content

WuuLibin/lab_github_API

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GitHub REST API

Overview

In Software development, an API (Application Programming Interface) is a set of rules and protocols that allows one software application to interact with another. APIs are used to define the methods and data formats that applications can use to communicate with each other. APIs are used to enable the integration of different software systems and allow them to work together.

Watch this video to learn more about REST API: What is a REST API?

The GitHub REST API allows you to interact with GitHub repositories using HTTP requests. It provides a way to interact with GitHub resources such as repositories, user profiles, and organizations. You can use the API to manage your GitHub resources using your own applications.

Visit https://api.github.com/.

  • This is the root endpoint of the GitHub API.
  • It returns a JSON object with a list of all the endpoints that you can access.

REST API Endpoints for GitHub

  1. The following endpoint will return a JSON object with information about the user. Replace the following {username} with the your GitHub username.
https://api.github.com/users/{username}
  1. The following endpoint will return a JSON object with a list of all the user's repositories. Replace the following {username} with the your GitHub username.
https://api.github.com/users/{username}/repos
  1. The following endpoint can be used to fetch information about a specific organization. Replace the following {org} with the organization name of this course.
https://api.github.com/orgs/{org}
  1. The following endpoint will return a JSON object with a list of all the organization's repositories. Replace the following {org} with the organization name of this course. If the request is not authenticated, it will only return the public repositories of the organization.
https://api.github.com/orgs/{org}/repos

a) What are the public repositories of the organization of this course?

b) The following endpoint will return a JSON object with information about a specific repository within an organization. Select one of the repositories in (a) and replace the following {org} with the organization name of this course and {repo} with the repository name.

https://api.github.com/repos/{org}/{repo}

c) Use the following endpoint to view all the issues of a repository. Replace the following {org} with the organization name of this course and {repo} with the repository name.

https://api.github.com/repos/{org}/{repo}/issues

d) Use the following endpoint to view all the commits of a repository. Replace the following {org} with the organization name of this course and {repo} with the repository name.

https://api.github.com/repos/{org}/{repo}/commits

API References for GitHub REST API.

Examples:

API for managing GitHub issues

https://docs.github.com/en/rest/issues

Getting all the issues in a repository

https://docs.github.com/en/rest/reference/issues#list-repository-issues

Getting an issue in a repository

https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28#get-an-issue

alt text

In REST API, you can use the GET method to retrieve information about a resource.

  • In the following example, you are using the GET method to retrieve information about the issue with number 1347 in the repository "Hello-World" owned by the user "octocat".
  • The "Authorization" header is used to authenticate the request using a personal access token.
GET /repos/octocat/Hello-World/issues/1347 HTTP/1.1
Host: api.github.com
Authorization: token [your_github_token]

The response will be a JSON object with information about the issue.

HTTP/1.1 200 OK
Server: GitHub.com
Date: Tue, 14 Dec 2021 12:30:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 521
Status: 200 OK
......

[
  {
    "id": 1,
    "node_id": "MDU6SXNzdWUx",
    "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347",
    "repository_url": "https://api.github.com/repos/octocat/Hello-World",
    "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}",
    "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments",
    "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events",
    "html_url": "https://github.com/octocat/Hello-World/issues/1347",
    "number": 1347,
    "state": "open",
    "title": "Found a bug",
    "body": "I'm having a problem with this.",
    ......
  },
  ......
]

Here are some common HTTP request methods in REST API:

  • GET: Retrieve information about the resource.
  • POST: Create a new resource.
  • PUT: Update an existing resource.
  • PATCH: Partially update an existing resource.
  • DELETE: Delete an existing resource.

The response of a REST API will be a JSON object with information about the issue. The HTTP response code indicates the status of the request.

  • 200: The request was successful.
  • 201: The request was successful and a new resource was created.
  • 204: The request was successful and the resource was deleted.
  • 404: The resource was not found.
  • 401: The request was unsuccessful due to an authentication error.
  • 403: The request was unsuccessful due to an authorization error.
  • 429: The request was unsuccessful due to a rate limit error.
  • 422: The request was unsuccessful due to a validation error.
  • 500: The request was unsuccessful due to a server error.

Examples: To create a new issue in a repository, you should use the POST method to the following endpoint to the endpoint: https://api.github.com/repos/{org}/{repo}/issues

alt text

Reference:
https://docs.github.com/en/rest/reference/issues#create-an-issue

Here is an example of a POST request to create a new issue in the repository "Hello-World" owned by the user "octocat". The request body contains the title and body of the issue.

POST /repos/{owner}/{repo}/issues
Accept: application/vnd.github.v3+json

{
  "title": "Found a bug",
  "body": "I'm having a problem with this."
}
HTTP/1.1 201 Created
Server: GitHub.com
Date: Tue, 14 Dec 2021 12:30:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 521
Status: 201 Created

{
  "id": 1,
  "node_id": "MDU6SXNzdWUx",
  "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347",
  "repository_url": "https://api.github.com/repos/octocat/Hello-World",
  "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}",
  "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments",
  "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events",
  "number": 1,
  "state": "open",
  "title": "Found a bug",
  "body": "I'm having a problem with this.",
  .....
}

Here is a table showing examples of the different HTTML methods performing various operations on the GitHub API.

HTTP Method Endpoint Description Success Response Code Failure Response Code
GET /repos/{owner}/{repo}/issues List all issues for a repository 200 404
GET /repos/{owner}/{repo}/issues/{issue_number} Get a single issue 200 404
POST /repos/{owner}/{repo}/issues Create a new issue 201 422
PATCH /repos/{owner}/{repo}/issues/{issue_number} Edit an issue 200 404, 422
GET /repos/{owner}/{repo}/issues/{issue_number}/comments List comments on an issue 200 404
POST /repos/{owner}/{repo}/issues/{issue_number}/comments Create a comment on an issue 201 422
PATCH /repos/{owner}/{repo}/issues/comments/{comment_id} Edit a comment on an issue 200 404, 422
DELETE /repos/{owner}/{repo}/issues/comments/{comment_id} Delete a comment 204 404

Writing a Python Script to Interact with GitHub API

How can we view all the issues and commits of all the repositories of an organization?

  1. Get a list of all repositories in an organization.
  2. For each repository, get a list of issue titles and commit messages.
import requests
org = 'organization'
token = 'your_github_token'
headers = {'Authorization': f'token {token}'}

# Get all repositories of the organization
response = requests.get(f'https://api.github.com/orgs/{org}/repos', headers=headers)
repos = response.json()

# For each repository, get the issues and commits
for repo in repos:
    # Get issues
    response = requests.get(f'https://api.github.com/repos/{org}/{repo["name"]}/issues', headers=headers)
    issues = response.json()
    for issue in issues:
        print(f"Issue: {issue['title']}")

    # Get commits
    response = requests.get(f'https://api.github.com/repos/{org}/{repo["name"]}/commits', headers=headers)
    commits = response.json()
    for commit in commits:
        print(f"Commit: {commit['commit']['message']}")

The authorization token can be obtained from your GitHub account settings:

  • Go to Settings -> Developer settings -> Personal access tokens. The token is used to authenticate your requests to the GitHub API and identify you as a user when making requests to the GitHub API.
  • It is a secret key that should be kept confidential and should not be shared with anyone.

Example:

alt text

SDK (Software DevelopmentKit) for GitHub API

PyGithub is a Python library to access the GitHub REST API. This library allows you to manage your GitHub resources, e.g. repositories, user profiles, and organizations in your Python applications.

https://pygithub.readthedocs.io/en/latest/introduction.html

Example:

from github import Github

# Get your personal access token from Github under Settings -> Developer settings -> Personal access tokens
g = Github("<access_token>")

# Print the list of repositories of the authenticated user
for repo in g.get_user().get_repos():
    print(repo.name)

Good Practices for Designing a REST API

Here are some guidelines when designing a REST API:

  • Use nouns to represent resources.
    • For example, /users, /repositories, /issues.
    • Do not use verbs in the URL, e.g. /createUser, /deleteIssue. The type of operation should be indicated by the HTTP method instead of using verbs in the URL.
  • Use HTTP methods to perform operations on resources. For example, GET to retrieve information, POST to create a new resource, PUT to update an existing resource, DELETE to delete a resource.
  • Use status codes to indicate the result of the request. For example, 200 for success, 404 for not found, 401 for unauthorized, 403 for forbidden, 429 for rate limit exceeded, 500 for server error.
  • Use JSON as the data format for request and response bodies. JSON is a lightweight data interchange format that is easy to read and write.
  • Use authentication to secure access to the API. For instance, GitHub API requires authentication using a personal access token to access certain resources.
  • Use pagination to limit the number of results returned in a single request. This helps to reduce the size of the response and improve performance.

GraphQL API

Overview

GraphQL is a query language for your API and a runtime for executing those queries using a type system you define for your data. Developed by Facebook in 2012 and released as an open-source project in 2015, GraphQL allows you to request only the data you need, unlike REST APIs, where multiple requests to different endpoints are often necessary.

GitHub provides a GraphQL API that allows you to interact with GitHub resources using GraphQL queries.

Explore the GitHub GraphQL API by signing in with your GitHub account.

https://docs.github.com/en/graphql/overview/explorer

Here are some shortcuts in the explorer:

  • Ctrl + Space: Show autocomplete suggestions.
  • Ctrl + Click: Jump to the definition of a field.
  • Ctrl + Enter: Run the query.

Types of Operations in GraphQL

  1. Query: Used to fetch or read data (similar to a GET request in REST).
  2. Mutation: Used to modify data (create, update, or delete). Each mutation operation is executed sequentially to avoid race conditions.
  3. Subscription: Establishes real-time connections with the server, allowing the server to push updates to the client.

Example Query Operation

  1. Try the following query operation in the explorer:
query {
  viewer {
    login
  }
}

This query returns the login ID of the authenticated user.

  1. To fetch details about a GitHub repository, such as the name, description, and the number of stars for the graphql-js repository, use:
query {
  repository(owner: "graphql", name: "graphql-js") {
    name
    description
    stargazerCount
  }
}

Here is a sample response:

{
  "data": {
    "repository": {
      "name": "graphql-js",
      "description": "A reference implementation of GraphQL for JavaScript",
      "stargazerCount": 19849
    }
  }
}
  1. To view all the repositories of a user (e.g., octocat):
query {
  user(login: "octocat") {
    repositories(first: 10) {
      nodes {
        name
      }
    }
  }
}

This GraphQL query retrieves information about the first 10 repositories of the organization with the login "github". Specifically, it fetches the name of each repository, the login of the repository owner, and the createdAt timestamp indicating when each repository was created. The organization field is used to specify the organization by its login name, and the repositories field with the first: 10 argument limits the results to the first 10 repositories. The nodes field is used to access the individual repository details.

query {
  organization(login: "github") {
    repositories(first: 10) {
      nodes{
          name
        	owner{
            login
          }
        	createdAt
        
      }
    }
  }
}

To view the first 10 issues of a specific repository:

query {
  repository(owner: "graphql", name: "graphql-js") {
    issues(first: 10) {
      nodes {
        title
      }
    }
  }
}

Exercise

  1. Construct a GraphQL query to show the repositories in the organization of this course and the number of commits and issues for each repository.
  2. Construct a GraphQL query to fetch the title, author and created time of the first 5 issues of the repository for the first lab in our course's Github organization.
  3. Construct a GraphQL query to show the first 5 commit messages, their dates, and the authors of those messages for each repository in the course organization.
  4. What do you observe about the difference between REST API and GraphQL API? What are the Pros and Cons of each type of API?

Mutation

GraphQL supports both query and mutation operations. A mutation is used to modify data. For example, to create a new issue in a repository, use:

mutation {
  createIssue(input: {
    repositoryId: "{your repository id}",
    title: "New Issue",
    body: "This is a new issue"
  }) {
    issue {
      title
      body
    }
  }
}

Here is a sample response:

{
  "data": {
    "addIssue": {
      "issue": {
        "title": "New Issue",
        "body": "This is a new issue"
      }
    }
  }
}

Exercise

Use the GraphQL API to create an issue in a repository owned by yourself.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published