GAS×API連携

GAS実践ガイド

GAS×API連携【外部サービスとの連携方法】

GASを使えば、様々なWebサービスのAPIと連携できます。この記事では、API連携の基本から実践的な活用方法までを解説します。

API連携の基本

APIとは

API(Application Programming Interface) は、外部サービスとプログラムで連携するための仕組みです。

できること

  • 天気情報の取得
  • 翻訳サービスの利用
  • SNSへの投稿
  • 決済サービスとの連携

GASでのAPI連携

基本的な流れ:
1. URLにリクエストを送信
2. レスポンス(JSON等)を受信
3. データを処理
4. スプレッドシートに出力

UrlFetchAppの使い方

GETリクエスト

JavaScript
function fetchGet() {
  const url = "https://api.example.com/data";
  const response = UrlFetchApp.fetch(url);

  // ステータスコード
  const code = response.getResponseCode();

  // レスポンスボディ
  const content = response.getContentText();

  Logger.log(content);
}

POSTリクエスト

JavaScript
function fetchPost() {
  const url = "https://api.example.com/data";
  const payload = {
    name: "田中",
    value: 100
  };

  const options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

ヘッダーの設定

JavaScript
function fetchWithHeaders() {
  const url = "https://api.example.com/data";

  const options = {
    method: "get",
    headers: {
      "Authorization": "Bearer YOUR_TOKEN",
      "Content-Type": "application/json"
    }
  };

  const response = UrlFetchApp.fetch(url, options);
  return JSON.parse(response.getContentText());
}

JSONデータの処理

JSONのパース

JavaScript
function parseJson() {
  const url = "https://api.example.com/users";
  const response = UrlFetchApp.fetch(url);
  const json = JSON.parse(response.getContentText());

  // 配列の場合
  json.forEach(user => {
    Logger.log(user.name);
  });

  // オブジェクトの場合
  Logger.log(json.data.value);
}

JSONをスプレッドシートに出力

JavaScript
function jsonToSheet() {
  const url = "https://api.example.com/users";
  const response = UrlFetchApp.fetch(url);
  const users = JSON.parse(response.getContentText());

  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.clear();

  // ヘッダー
  const headers = Object.keys(users[0]);
  sheet.appendRow(headers);

  // データ
  users.forEach(user => {
    const row = headers.map(h => user[h]);
    sheet.appendRow(row);
  });
}

JSONの作成

JavaScript
function createJson() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const data = sheet.getDataRange().getValues();
  const headers = data[0];

  const json = [];
  for (let i = 1; i < data.length; i++) {
    const obj = {};
    headers.forEach((h, j) => {
      obj[h] = data[i][j];
    });
    json.push(obj);
  }

  return JSON.stringify(json);
}

認証付きAPI

APIキー認証

JavaScript
function fetchWithApiKey() {
  const apiKey = "YOUR_API_KEY";
  const url = `https://api.example.com/data?api_key=${apiKey}`;

  const response = UrlFetchApp.fetch(url);
  return JSON.parse(response.getContentText());
}

Bearer認証

JavaScript
function fetchWithBearer() {
  const token = "YOUR_ACCESS_TOKEN";
  const url = "https://api.example.com/data";

  const options = {
    method: "get",
    headers: {
      "Authorization": `Bearer ${token}`
    }
  };

  const response = UrlFetchApp.fetch(url, options);
  return JSON.parse(response.getContentText());
}

OAuth2認証

JavaScript
// OAuth2ライブラリを使用(要インストール)
function getOAuthService() {
  return OAuth2.createService("ServiceName")
    .setAuthorizationBaseUrl("https://example.com/oauth/authorize")
    .setTokenUrl("https://example.com/oauth/token")
    .setClientId(CLIENT_ID)
    .setClientSecret(CLIENT_SECRET)
    .setCallbackFunction("authCallback")
    .setPropertyStore(PropertiesService.getUserProperties())
    .setScope("read write");
}

認証情報の安全な保存

JavaScript
// スクリプトプロパティに保存
function setApiKey(key) {
  PropertiesService.getScriptProperties()
    .setProperty("API_KEY", key);
}

// 取得
function getApiKey() {
  return PropertiesService.getScriptProperties()
    .getProperty("API_KEY");
}

実践例

例1: 天気情報の取得

JavaScript
function getWeather(city) {
  const apiKey = getApiKey();
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=ja`;

  const response = UrlFetchApp.fetch(url);
  const data = JSON.parse(response.getContentText());

  return {
    city: data.name,
    temp: data.main.temp,
    description: data.weather[0].description
  };
}

function recordWeather() {
  const weather = getWeather("Tokyo");
  const sheet = SpreadsheetApp.getActiveSheet();

  sheet.appendRow([
    new Date(),
    weather.city,
    weather.temp,
    weather.description
  ]);
}

例2: Slack通知

JavaScript
function sendSlackMessage(message) {
  const webhookUrl = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL";

  const payload = {
    text: message,
    username: "GAS Bot",
    icon_emoji: ":robot_face:"
  };

  const options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(payload)
  };

  UrlFetchApp.fetch(webhookUrl, options);
}

// 使用例
function notifySlack() {
  sendSlackMessage("スプレッドシートが更新されました");
}

例3: ChatGPT API連携

JavaScript
function askChatGPT(prompt) {
  const apiKey = getApiKey();
  const url = "https://api.openai.com/v1/chat/completions";

  const payload = {
    model: "gpt-3.5-turbo",
    messages: [
      { role: "user", content: prompt }
    ]
  };

  const options = {
    method: "post",
    headers: {
      "Authorization": `Bearer ${apiKey}`,
      "Content-Type": "application/json"
    },
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response.getContentText());

  return data.choices[0].message.content;
}

例4: Google Maps API

JavaScript
function geocode(address) {
  const apiKey = getApiKey();
  const encodedAddress = encodeURIComponent(address);
  const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${apiKey}`;

  const response = UrlFetchApp.fetch(url);
  const data = JSON.parse(response.getContentText());

  if (data.results.length > 0) {
    const location = data.results[0].geometry.location;
    return {
      lat: location.lat,
      lng: location.lng
    };
  }
  return null;
}

エラーハンドリング

基本的なエラー処理

JavaScript
function fetchWithErrorHandling(url) {
  try {
    const response = UrlFetchApp.fetch(url, {
      muteHttpExceptions: true
    });

    const code = response.getResponseCode();

    if (code === 200) {
      return JSON.parse(response.getContentText());
    } else if (code === 401) {
      throw new Error("認証エラー");
    } else if (code === 404) {
      throw new Error("リソースが見つかりません");
    } else if (code >= 500) {
      throw new Error("サーバーエラー");
    }
  } catch (e) {
    Logger.log(`エラー: ${e.message}`);
    return null;
  }
}

リトライ処理

JavaScript
function fetchWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = UrlFetchApp.fetch(url);
      return JSON.parse(response.getContentText());
    } catch (e) {
      Logger.log(`リトライ ${i + 1}/${maxRetries}: ${e.message}`);
      Utilities.sleep(1000 * (i + 1)); // 指数バックオフ
    }
  }
  throw new Error("最大リトライ回数を超えました");
}

注意点

実行時間の制限

  • 1回の実行: 最大6分
  • 長いAPI処理は分割して実行

API呼び出し制限

  • UrlFetchApp: 1日20,000回(無料アカウント)
  • APIサービス側の制限も確認

セキュリティ

  • APIキーはスクリプトプロパティに保存
  • ソースコードに直接書かない
  • 必要最小限の権限で

まとめ

API連携の基本

JavaScript
// GETリクエスト
const response = UrlFetchApp.fetch(url);
const data = JSON.parse(response.getContentText());

// POSTリクエスト
const options = {
  method: "post",
  contentType: "application/json",
  payload: JSON.stringify(data)
};
UrlFetchApp.fetch(url, options);

活用のポイント

  1. 公式ドキュメントをよく読む
  2. エラーハンドリングを実装
  3. 認証情報は安全に保存
  4. APIの利用制限を確認

関連記事

お問い合わせ

GAS×API連携についてのご相談は、お気軽にお問い合わせください。

  • API連携開発
  • 自動化システム構築
  • 技術サポート

お問い合わせはこちら

最終更新: 2025年1月