Programming Language/Java

[Java] Github API 사용하기

  • -

프로젝트를 하면서 Github API를 사용하게 되었는데,

사용하는 방법을 소개해 드리도록 하겠습니다!

의존성 추가하기

https://mvnrepository.com/artifact/org.kohsuke/github-api

먼저 위 문서에서 Project Documentation - Project Information - Dependencies 에 들어가

API를 사용할 수 있도록 의존성을 추가하겠습니다.

가장 최근 버전을 선택하고

자신의 프로젝트와 맞게 선택한 후 의존성을 추가해주세요

implementation group: 'org.kohsuke', name: 'github-api', version: '1.315'

저는 gradle을 사용하기 때문에 위 코드를 dependencies에 추가했습니다.

 

사용해보기

https://github-api.kohsuke.org/

 

GitHub API for Java –

What is this? This library defines an object oriented representation of the GitHub API. By "object oriented" we mean there are classes that correspond to the domain model of GitHub (such as GHUser and GHRepository), operations that act on them as defined a

github-api.kohsuke.org

위 문서의 코드를 참고하여 테스트를 해보겠습니다.

 

토큰으로 인증하기

먼저 깃허브 객체를 생성해보겠습니다.

Github gitHub = new GitHubBuilder().withOAuthToken(TOKEN).build();

TOKEN에 본인의 깃허브 토큰을 써주시면 됩니다.

gitHub.checkApiUrlValidity();

위 코드를 추가하고 실행시켰을 때, 토큰이 유효하지 않으면 에러가 발생합니다.

 

리포지토리 불러오기

GHRepository repo = gitHub.getRepository("유저아이디/리포지토리이름");

유저아이디/리포지토리이름 형식의 문자열로 리포지토리를 불러올 수 있습니다.

 

 

유저 불러오기

 

GHUser user = gitHub.getUser("유저아이디");

유저 아이디를 입력하여 유저 객체를 받아올 수 있습니다.

 

사용 예시

package org.example.api;

import org.kohsuke.github.*;

public class GithubApi {

    final String TOKEN = "본인의 깃허브 토큰을 입력하세요";
    private GitHub gitHub;

    public static void main(String[] args) {
        GithubApi githubApi = new GithubApi();
        githubApi.connectGithub();
    }

    public void connectGithub(){
        try {
            this.gitHub = new GitHubBuilder().withOAuthToken(TOKEN).build();
            this.gitHub.checkApiUrlValidity();

            // 리포지토리 이름으로 불러오기
            GHRepository repo = gitHub.getRepository("hyeg0121/The_Color_of_the_sky");
            System.out.println("리포지토리 이름 : " + repo.getFullName());
            System.out.println("디폴트 브랜치 : " + repo.getDefaultBranch());
            System.out.println("오너 이름 : " + repo.getOwner().getName());

            // 유저 불러오기
            GHUser user = gitHub.getUser("hyeg0121");
            System.out.println("유저 이름 : " + user.getName());
            System.out.println("팔로워 : " + user.getFollowersCount());
            System.out.println("팔로잉 : " + user.getFollowingCount());
            System.out.println("회사 : " + user.getCompany());


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        
    }
}

GHRepository와 GHUser 객체를 통해 여러 정보를 가져올 수 있습니다!

실제 클래스에 어떤 메서드가 있는지 보고, 사용하시는 것을 추천드립니다.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.