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?

More than 1 year has passed since last update.

【GAS】APIの実行をする

Last updated at Posted at 2023-01-01

概要

API叩いてログ出力する
今回はQiita APIを使用する

手順

  1. APIのトークンのKeyを発行する
  2. 実行する
  3. 取得できる

APIのトークンのKeyを取得する

まあトークンとかAPI Keyの取得は各々のAPIの仕様によって若干異なるけど、大体取得方法は丁寧に説明されているからその通りに取得すればいい

その値はGitHubとかに公開していけない秘密の値で、信用できない人には見せないって覚えておけば問題ない

今回は下記の記事を参考に取得

実行する

  • スプレッドシート経由なりとかでApps Scriptの編集画面をひらく

  • 下記コードを書く

    const BASE_URL = 'https://qiita.com';
    
    const USER_NAME = 'ユーザー名';
    const API_KEY = 'トークンのキー';
    
    const executeApi = () => {
      // header
      let requestHeader = {
        'Authorization': `Bearer ${API_KEY}`,
        'Accept': 'application/json'
      }
      // option
      let requestOptions = {
        'method': 'get',
        'headers': requestHeader,
        "muteHttpExceptions": true
      }
    
      try {
        let requestUrl = `${BASE_URL}/api/v2/users/${USER_NAME}`;
        let response = UrlFetchApp.fetch(requestUrl, requestOptions);
    
        let resCode = response.getResponseCode();
        let resBody = response.getContentText();
    
        Logger.log(`code: ${resCode}`);
        Logger.log(`body: ${resBody}`);
      } catch (e) {
        Logger.log(e);
      }
    }
    
  • 実行する関数を選択し、「実行」ボタンを押す

    画面の上の方に実行ボタンとかがあるので、実行する関数(今回はexecuteApi)を選択

    スクリーンショット 2023-01-02 1.15.20.png

取得できる

実行すると、下記画像のように実行ログが表示され、自分の情報が出力される

スクリーンショット 2023-01-02 1.21.30.png

最後に

今回はここで終わりだが、まあスプレッドシートに出力するとかこの関数で中身を文字列でかえすとかするときはパースしてなんか色々やる感じで

// たとえば
let obj = JSON.parse(resBody);
let body = obj['body'];
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?