LoginSignup
0
0

More than 1 year has passed since last update.

AirtableをAPIとしてnodeJSを使いJSONデータ化するまで

Last updated at Posted at 2021-11-30

JSONを吐かせる簡易DB代わりにGoogleSpreadSheetを使っているのですが使っているGAS使ってるシートとそうでないシートとでごちゃごちゃしてきてしまったので無料で使えて代替手段となるものはないのかな〜ということでAirtableを使ってみることに。

(気になってたからってのもある)

ワークスペースの準備

スクリーンショット 2021-11-30 16.59.02.png

初めに、ワークスペースとしてTestテーブルを作成しておきます。シート名も"TestTable"としておきました。

APIキーの取得

airtable.jpg

「右上のアイコン > Account」へ飛ぶとAPIキーを生成できるので生成して保存しておきます。

スクリーンショット 2021-11-30 16.30.55.png

TestテーブルのIDの取得

そして https://airtable.com/api/ へ飛ぶと自分のワークスペース専用ドキュメントができているという素晴らしきユーザー体験

画像の "Test"(あなたの任意のワークスペース) へ飛びます。

スクリーンショット 2021-11-30 17.03.32.png

https://airtable.com/あなたのテーブルID/api/docs#javascript/ratelimits

するURLにテーブルIDがあるので "あなたのテーブルID" を保存しておきます。

試しに Name の列のカラムを取得してみる

ディレクトリ構成(node_modulesなどは省く)

AirtableTest/
 generated/
 .env
 index.js
 package.json

適当に yarn init などしておきディレクトリ準備。

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

yarn add -D airtable dotenv

scriptsを追加して実行コマンドも設定しておく。

package.json
省略
  "scripts": {
    "start": "node -r dotenv/config index.js"
  }
省略

環境変数の設定

AIRTABLE_API_KEY=あなたのAPIキー

テーブルのName列のカラムを取得する処理

index.js
const base = require('airtable').base('あなたのテーブルID');
const app = base("TestTable")
const airtableLists = app.select({view: "Grid view"})
airtableLists.firstPage((error, records) => {
  const names = records.map(record =>
    record.get("Name")
  )
  console.log(names);
});

実行してみる

yarn start
yarn run v1.22.10
$ node -r dotenv/config index.js
[ 'hoge', 'hage', 'fuga', undefined ]
✨  Done in 2.35s.

と上のような値が返って来ればOKです。

JSON化する

ここで取得したデータをJSONデータ化させてみます。

index.js
const fs = require('fs');
const base = require('airtable').base('あなたのテーブルID');
const app = base("TestTable");
const airtableLists = app.select({view: "Grid view"});

const createJSON = (airtableObj) => {
  const JSONdata = JSON.stringify(airtableObj, null, 2);
  fs.writeFileSync('generated/airtable.json', JSONdata);
}

const getAirtableObj = (airtableLists) => {
  return airtableLists.firstPage((error, records) => {
    const airtableObj = records.map(record => ({ Name: record.get("Name"), Notes: record.get("Notes") }));
    createJSON(airtableObj);
  });
}

getAirtableObj(airtableLists);

ここで generated/airtable.json にルート指定して生成します。

const createJSON = (airtableObj) => {
  const JSONdata = JSON.stringify(airtableObj, null, 2);
  fs.writeFileSync('generated/airtable.json', JSONdata);
}

生成されたJSONを確認してみる

空白だったカラムは空になっていますが以下のように取得できていることがわかります。

airtable.json
[
  {
    "Name": "hoge",
    "Notes": "ほい"
  },
  {
    "Name": "hage",
    "Notes": "はい"
  },
  {
    "Name": "fuga",
    "Notes": "へい"
  },
  {}
]
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