LoginSignup
0

More than 1 year has passed since last update.

GitHub APIでユーザーの情報をJSONで取得し、画面に表示する

Last updated at Posted at 2023-01-22

はじめに

GitHubについて勉強したので、メモとして残していきたいと思います。

GitHub APIとは?

GitHubが提供しているAPIで、GitHubに登録しているユーザーの情報や、そのユーザーのリポジトリの情報など、様々なデータをJSONで取得できるAPIになります。
今回は、取得したリポジトリの一覧を、JavaScriptで画面に表示をしていこうと思います。

リポジトリの情報を取得する

今回は自分が公開をしているGitHubを使用していきます。
以下のURLでAPIを用いて、自分のユーザーデータから、リポジトリ一覧情報を取得することができます。

https://api.github.com/users/GitHubの登録ユーザー名/repos

今回使用するURLはこちらです。hukuryoというユーザーのリポジトリ一覧を取得します。

https://api.github.com/users/hukuryo/repos

表示される画面がこちらです。↓
スクリーンショット 2023-01-22 9.14.18.png

このように、リポジトリの一覧が取得できました。
色々な情報を取得できていますが、nameというカラムがリポジトリの名前になります。

取得したJSONをHTMLに反映する。

次は、取得したJSONをJavaScriptでHTMLに表示していきたいと思います。コードはこちらです。

script.js
const button = document.getElementById('click');
const type = document.getElementById('type');
button.addEventListener('click', () => {
    let url = 'https://api.github.com/users/hukuryo/repos';
    fetch(url)
      .then(response => response.json())
      .then(data => {
        for(let i = 0; i < data.length; i++){
          newElement = document.createElement("div");
          newElement.innerHTML = data[i].name;
          type.appendChild(newElement);
          console.log(data[i].name);
        }
    });
});
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>sample</title>
    </head>
    <body>
    <button id='click'>sample</button>
    <div><span id='type'></div>
    <script src="script.js"></script>
</body>
</html>

そしてこれが実際の画面です。↓
スクリーンショット 2023-01-22 9.18.18.png

ボタンを押すと...

スクリーンショット 2023-01-22 9.19.25.png

JSONで取得したデータをHTMLに反映することができました!
GitHub APIには、他にも様々な機能があるので下記のURLから調べてみてください!
https://docs.github.com/ja/rest?apiVersion=2022-11-28

以上になります。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0