0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Classroom APIを使ってみる

0
Last updated at Posted at 2025-12-12

本記事は、めんどい太郎の Advent Calendar 2025 13日目の記事です。

はじめに

Google Classroom APIを使っていろいろ作りたくなったので、使い方をまとめておきます。

Google Classroom APIとは

Google Classroomを操作することができるAPIです。

お知らせの取得などいろいろなことができます。便利。

環境

今回はNode.jsを使ってAPIを触ってみます。

使ってみる

事前準備

Google Cloud Platformでの準備

Google Cloud Platformでプロジェクトを作成し、Google Classroom APIを有効化します。

コンソールにアクセスします。

新しいプロジェクトを作成します。

image.png

メニューから「APIとサービス」=>「ライブラリ」を開きます。

image.png

APIの一覧が出てきます。

image.png

「Classroom」を検索します。

image.png

「Google Classroom API」を選択して、有効にします。

image.png

有効になりました。

image.png

お次は認証情報を作成します。

先ほどの画面に出ている「認証情報の作成」を押します。

APIを「Google Classroom API」に、アクセスするデータの種類を「ユーザーデータ」にします。

image.png

次へを押します。

アプリ情報のアプリ名、ユーザーサポートメール、そしてデベロッパーの連絡先にメールアドレスを入力します。

image.png

「保存して次へ」を押します。

「スコープの追加または削除」を押します。

image.png

ここではGoogle Classroom APIについての次のスコープを追加します。

  • .../auth/classroom.courses.readonly
  • .../auth/classroom.student-submissions.me.readonly
  • .../auth/classroom.course-work.readonly
  • .../auth/classroom.coursework.me

選択したら「更新」を押します。

無事にスコープが追加されていればOKです。

image.png

「保存して次へ」を押します。

アプリケーションの種類を「ウェブ アプリケーション」にします。

image.png

「承認済みの JavaScript 生成元」をhttp://localhost:3000

「 承認済みのリダイレクト URI」をhttp://localhost:3000/oauth2callback

にしてください。

image.png

「作成」を押します。

認証情報が作成されました。

クライアントIDをメモしておき、認証情報をダウンロードします。

image.png

最後に、「完了」を押します。

メニューから「OAuth同意画面」を開きます。

image.png

メニューから「対象」を開きます。

image.png

「テストユーザー」の「Add users」を押します。

image.png

ClassroomでログインしたいGoogleアカウントを追加し、保存を押します。

image.png

これで完了です。

ライブラリのインストール

次に、Node.jsのGoogle APIs Node.js Clientというライブラリをインストールします。

npm install googleapis
npm i server-destroy

これで完了です。

プログラムを書いてみる

では、実際にプログラムを書いてみます。

といってもほとんどサンプルまんまです。

index.js
'use strict';

const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');
const destroyer = require('server-destroy');

const {google} = require('googleapis');
const classroom = google.classroom('v1');

const keyPath = path.join(__dirname, 'PATH_TO_SERVICE_ACCOUNT_KEY.json');
let keys = {redirect_uris: ['']};
if (fs.existsSync(keyPath)) {
  keys = require(keyPath).web;
}

const oauth2Client = new google.auth.OAuth2(
  keys.client_id,
  keys.client_secret,
  keys.redirect_uris[0],
);

google.options({auth: oauth2Client});

async function authenticate(scopes) {
  return new Promise((resolve, reject) => {
    const authorizeUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' '),
    });
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            const {tokens} = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens;
            resolve(oauth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        console.log(authorizeUrl);
      });
    destroyer(server);
  });
}

async function runSample() {
  const res = await classroom.courses.list({
    pageSize: 10,
  });
  console.log(res.data);
}

const scopes = [
  'https://www.googleapis.com/auth/classroom.courses.readonly',
  'https://www.googleapis.com/auth/classroom.student-submissions.me.readonly',
  'https://www.googleapis.com/auth/classroom.course-work.readonly',
  'https://www.googleapis.com/auth/classroom.coursework.me'
];
authenticate(scopes)
  .then(client => runSample(client))
  .catch(console.error);

PATH_TO_SERVICE_ACCOUNT_KEY.jsonは先ほどダウンロードした認証情報のパスに変更してください。

実行してみる

さっそく実行してみます。

$ node .
https://accounts.google.com/o/oauth2/v2/auth?access_type=offline........

こんな感じでログイン用のURLが表示されますのでアクセスします。

注意されますが続行します。

image.png

アクセス権限の設定ができます。とりあえずすべて選択しておきましょう。

image.png

続行を押すと...

Authentication successful! Please return to the console.

というメッセージが表示され、コンソールを見ると...

{
  courses: [
    {
      id: '**************************************',
      name: '**************************************',
      section: '**************************************',
      ownerId: '**************************************',
      creationTime: '**************************************',
      updateTime: '**************************************',
      courseState: '**************************************',
      alternateLink: '**************************************',
      teacherGroupEmail: '**************************************',
      courseGroupEmail: '**************************************',
      guardiansEnabled: **************************************,
      calendarId: '**************************************',
      gradebookSettings: [Object]
    },
    ........
  ],
  nextPageToken: '**************************************'
}

といった感じでAPIが実行できていることがわかります。

ちゃんと所属しているクラスの情報が表示されました!

(念のため加工してすべて消しています。)

終わりに

Google Classroom APIを使ってみました。

とりあえず、APIを触るところまでできました。

Googleさんはドキュメントが豊富でわかりやすかったり、サンプルを置いてくれていることが多かったりするので助かりますね...!

今後、Google Classroom APIを使って何かを作りたいところ...

もし何か作ったらまた記事にしますね!

それでは!

参考

0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?