LoginSignup
1
1

現在いるセルのURLを叩いてレスポンスを右側に格納する[GAS/Google Apps Script]書いた

Posted at

はじめに

いい感じのスクリプト書いたので忘れないように投稿しておく。

イメージ

スクリーンショット 2023-11-16 22.21.15.png

コード

fetchするURLは https://httpbin.org/get

gasのコードはこんな感じ

function fetchApi() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getActiveSheet();
  const cell = sheet.getCurrentCell();
  const [col, row, url] = [cell.getColumn(), cell.getRow(), cell.getValue()];

  const res = UrlFetchApp.fetch(url);
  const result = res.getContentText();
  const code = res.getResponseCode();

  sheet.getRange(row, col + 1, 1, 1).setValue(`CODE: ${code}, RESULT: ${result}`);
}


  • 今いるセルのURLを取ってくる
  • Fetchする
  • 右隣に結果を書き込む

設定

Apps Script

スクリーンショット 2023-11-16 22.22.25.png

図形描画

スクリーンショット 2023-11-16 22.22.47.png

図形へのスクリプト割当

fetchApi を設定

スクリーンショット 2023-11-16 22.23.08.png

認証関連もろもろ

自分が作ったスクリプトなのにかなり権限しつこく聞かれる。
基本的に他人が作ったスクリプトに権限渡さない。Googleの認証とかこのあと入る

スクリーンショット 2023-11-16 22.07.56.png

終わりに

今回は具体的にはJamstackでお世話になりやすい https://microcms.io/ さんのブログ取得APIを使って、microcms側でブログを書いて、定期的にスプレッドシートにコンテンツを出力、それをコピペしてhtmlに埋め込む、みたいなことやってて必要になったので作りました。

その場合、以下のような書き方に一部変更されますが、概ね簡単な作業でできたので満足です。

  const options = {
    'method' : 'get',
    'headers': {
      "X-MICROCMS-API-KEY": "あなたのAPIキー"
    }
  };
  const res = UrlFetchApp.fetch(url, options);
  const content = JSON.parse(res.getContentText()).content
1
1
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
1
1