この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:6
ページ更新者:T
更新日時:2026-06-11 07:29:05

タイトル: GETリクエストする方法
SEOタイトル: Google Apps Script (GAS) GET リクエスト完全ガイド (UrlFetchApp / ヘッダ / JSON / レート制限)

この記事の要点
  • GAS で GET: UrlFetchApp.fetch(url, {method: "get"}) (method 省略時 GET)
  • レスポンス: getContentText() (本文)、getResponseCode() (HTTP コード)、getHeaders()
  • クエリパラメータは encodeURIComponent で URL エンコード必須
  • エラーで例外を投げない: { muteHttpExceptions: true }
  • 並列リクエストは UrlFetchApp.fetchAll、1 日 20,000 (有償 100,000) のクォータ上限あり

基本: UrlFetchApp.fetch

function basicGet() {
  // 最もシンプルな GET
  const response = UrlFetchApp.fetch('https://api.github.com/users/octocat');

  // 本文取得
  const text = response.getContentText();
  Logger.log(text);

  // JSON ならパース
  const data = JSON.parse(text);
  Logger.log(data.name);  // The Octocat
}

主要メソッド

メソッド説明
getContentText()レスポンス本文を文字列で取得 (UTF-8)
getContentText(charset)文字コード指定 (例: "Shift_JIS")
getContent()バイナリ (Byte[]) で取得
getResponseCode()HTTP ステータスコード (200, 404, 500 等)
getHeaders()レスポンスヘッダ (オブジェクト)
getAllHeaders()同じヘッダ複数回ある場合に対応 (配列)
getBlob()Blob オブジェクトで取得 (画像保存等)

クエリパラメータの組み立て

function getWithQuery() {
  const baseUrl = 'https://api.example.com/search';

  const params = {
    q: 'Apps Script 入門',
    page: 1,
    per_page: 20,
    lang: 'ja',
  };

  // URL クエリ文字列を組み立て
  const query = Object.keys(params)
    .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
    .join('&');

  const url = `${baseUrl}?${query}`;
  // → https://api.example.com/search?q=Apps%20Script%20%E5%85%A5%E9%96%80&page=1&per_page=20&lang=ja

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

ヘッダ付き GET (認証など)

function getWithHeaders() {
  const url = 'https://api.github.com/user/repos';

  const options = {
    method: 'get',
    headers: {
      'Authorization': 'token ghp_xxxxxxxxxxxxxxxxxxxx',
      'Accept': 'application/vnd.github.v3+json',
      'User-Agent': 'MyAppsScript',
    },
    muteHttpExceptions: true,
  };

  const response = UrlFetchApp.fetch(url, options);

  if (response.getResponseCode() === 200) {
    const repos = JSON.parse(response.getContentText());
    repos.forEach(r => Logger.log(r.full_name));
  } else {
    Logger.log('Error: ' + response.getResponseCode());
    Logger.log(response.getContentText());
  }
}

エラーハンドリング

デフォルトでは HTTP 4xx / 5xx の場合 GAS が例外を投げます。レスポンスコードを自分で見たい場合は muteHttpExceptions: true を指定:

function safeGet() {
  const url = 'https://api.example.com/possibly-fails';

  try {
    const response = UrlFetchApp.fetch(url, {
      muteHttpExceptions: true,  // ★ 4xx / 5xx でも例外投げない
    });

    const code = response.getResponseCode();
    const body = response.getContentText();

    if (code === 200) {
      return JSON.parse(body);
    } else if (code === 401) {
      throw new Error('認証エラー: API キーを確認');
    } else if (code === 429) {
      // レート制限 → 待機してリトライ
      Utilities.sleep(60 * 1000);
      return safeGet();
    } else if (code >= 500) {
      throw new Error(`サーバエラー: ${code} ${body}`);
    } else {
      throw new Error(`HTTP ${code}: ${body}`);
    }
  } catch (e) {
    Logger.log(`Fetch error: ${e}`);
    // 通知 / Sheets に記録
    SpreadsheetApp.getActive().toast(`API エラー: ${e.message}`);
    return null;
  }
}

並列リクエスト fetchAll

複数 URL を順次叩くと遅いので、UrlFetchApp.fetchAll で並列実行:

function parallelGet() {
  const requests = [
    { url: 'https://api.example.com/users/1', method: 'get' },
    { url: 'https://api.example.com/users/2', method: 'get' },
    { url: 'https://api.example.com/users/3', method: 'get' },
    {
      url: 'https://api.example.com/users/4',
      method: 'get',
      headers: { Authorization: 'Bearer xxx' },
      muteHttpExceptions: true,
    },
  ];

  // ★ 並列実行 (10 倍程度高速になることも)
  const responses = UrlFetchApp.fetchAll(requests);

  responses.forEach((r, i) => {
    if (r.getResponseCode() === 200) {
      Logger.log(`#${i+1}: ${r.getContentText().substring(0, 80)}...`);
    } else {
      Logger.log(`#${i+1}: ERROR ${r.getResponseCode()}`);
    }
  });
}

実用例1: 為替レート取得 → Sheets に書込

function logExchangeRate() {
  const url = 'https://api.exchangerate-api.com/v4/latest/USD';
  const response = UrlFetchApp.fetch(url);
  const data = JSON.parse(response.getContentText());

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('rates');
  sheet.appendRow([
    new Date(),
    data.rates.JPY,
    data.rates.EUR,
    data.rates.GBP,
  ]);
}

// トリガー: 毎日午前 9 時に自動実行
// 編集メニュー → 現在のプロジェクトのトリガー → 時間主導型 → 日タイマー

実用例2: Slack に通知

function notifySlackOnError() {
  const slackWebhook = PropertiesService.getScriptProperties()
    .getProperty('SLACK_WEBHOOK_URL');

  // 監視先 URL を GET
  const response = UrlFetchApp.fetch('https://example.com/health', {
    muteHttpExceptions: true,
  });

  if (response.getResponseCode() !== 200) {
    UrlFetchApp.fetch(slackWebhook, {
      method: 'post',
      contentType: 'application/json',
      payload: JSON.stringify({
        text: `🚨 https://example.com/health が落ちています (HTTP ${response.getResponseCode()})`,
      }),
    });
  }
}

実用例3: Twitter / X API (Bearer 認証)

function searchTweets() {
  const bearer = PropertiesService.getScriptProperties()
    .getProperty('X_BEARER_TOKEN');

  const query = encodeURIComponent('Apps Script lang:ja -is:retweet');
  const url = `https://api.x.com/2/tweets/search/recent?query=${query}&max_results=20`;

  const response = UrlFetchApp.fetch(url, {
    headers: { 'Authorization': `Bearer ${bearer}` },
    muteHttpExceptions: true,
  });

  if (response.getResponseCode() === 200) {
    const data = JSON.parse(response.getContentText());
    data.data.forEach(t => Logger.log(t.text));
  } else {
    Logger.log(response.getContentText());
  }
}

クォータ (利用上限)

項目無料アカウントGoogle Workspace
UrlFetch リクエスト数 / 日20,000100,000
UrlFetch 応答サイズ上限50 MB50 MB
UrlFetch URL 長上限2 KB2 KB
UrlFetch ヘッダサイズ8 KB8 KB
UrlFetch POST サイズ50 MB50 MB
実行時間上限 (1 回)6 分30 分

クォータを超えると Service invoked too many times エラー。fetchAll で並列化 + キャッシュ利用 (CacheService) でリクエスト数を抑えるのが定石。

キャッシュ活用

function cachedFetch(url) {
  const cache = CacheService.getScriptCache();
  const key = 'fetch_' + Utilities.base64Encode(url);

  let cached = cache.get(key);
  if (cached) {
    Logger.log('Cache hit');
    return JSON.parse(cached);
  }

  const response = UrlFetchApp.fetch(url);
  const text = response.getContentText();

  // 10 分キャッシュ (最大 6 時間)
  cache.put(key, text, 600);

  return JSON.parse(text);
}

FAQ

Q: 文字化けする
A: getContentText("Shift_JIS")getContentText("EUC-JP") で明示。日本のレガシー API でよく必要。

Q: HTTPS 証明書エラーが出る
A: GAS は基本的に証明書検証必須。自己署名証明書の API は呼べません。Cloud Functions 等を経由してください。

Q: 同期処理しかできない?
A: GAS は基本同期。並列が必要なら fetchAll。複数 API を 5 件ずつ並列化するなどの工夫で実用速度が出ます。