1
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?

Pythonでkintoneのレコードを一括取得する方法

Posted at

Pythonでkintoneのレコードを一括取得する方法

こんにちは、今回はPythonを使ってkintoneからレコードを取得する方法をご紹介します!

kintoneはノーコードでアプリを作れる便利なプラットフォームですが、データを分析したりバックアップしたりするには、APIを使ってデータを取得する必要があります。この記事では、初心者でも分かるように、基本的なレコード取得処理のPythonコードと解説をまとめました。


🔧 事前準備

kintoneのデータをPythonから取得するには、以下の情報が必要です。

✅ BASE_URL(ベースURL)

kintoneのサブドメインを含んだURLです。

  • 例: https://example.cybozu.com

✅ APP_ID(アプリID)

kintoneのアプリを開いたときのURLの末尾にある数字です。

  • 例: https://example.cybozu.com/k/123/ → この場合は 123 がAPP_ID

✅ API_TOKEN(APIトークン)

アプリの「設定」>「APIトークン」から生成できます。

  • レコードの閲覧権限が必要です(必要に応じて追加)。

環境変数 .env ファイルなどに以下のように記載しておくと便利です。

BASE_URL=https://example.cybozu.com
APP_ID=123
API_TOKEN=your_kintone_api_token

🐍 Pythonコード

以下のコードは、kintoneから全レコードを100件ずつページングしながら取得し、PandasのDataFrameとして扱えるように変換します。

import os
import json
import requests
import pandas as pd
from dotenv import load_dotenv

load_dotenv()

BASE_URL = os.getenv('BASE_URL')
APP_ID = os.getenv('APP_ID')
API_TOKEN = os.getenv('API_TOKEN')

def get_kintone_df():
    limit = 100  # 1ページあたりのレコード数
    offset = 0  # オフセットの初期値
    all_records = []

    while True:
        url = f'{BASE_URL}/k/v1/records.json'
        headers = {
           "X-Cybozu-API-Token": API_TOKEN,
        }
        params = {
            'app': APP_ID,
            'query': f'order by $id asc limit {limit} offset {offset}'
        }
        response = requests.get(url, headers=headers, params=params)
        res_dict = json.loads(response.text)

        if 'records' in res_dict:
            records = res_dict['records']
            all_records.extend(records)

        if len(records) < limit:
            break
        offset += limit

    df_records = pd.DataFrame.from_records(all_records)
    # 各フィールドのvalueだけを抽出
    for column in df_records.columns:
        df_records[column] = df_records[column].map(lambda x: x['value'] if isinstance(x, dict) else x)

    return df_records

# 実行してみる
if __name__ == "__main__":
    df = get_kintone_df()
    print(df.head())

💡 解説ポイント

🔁 なぜループが必要?

kintoneのAPIは一度に取得できるレコードが最大100件までのため、
それ以上のデータを取得したい場合はオフセットを使って繰り返し取得する必要があります。

🏷 フィールドコードと列名の関係

kintoneのフィールドは、**「フィールドコード」**という識別子を使ってAPIでアクセスされます。
取得したレコードは次のような形式になっていて:

{
  "顧客名": {"type": "SINGLE_LINE_TEXT", "value": "株式会社サンプル"},
  "住所": {"type": "SINGLE_LINE_TEXT", "value": "東京都渋谷区"},
  ...
}

このままだと扱いづらいため、x['value'] を取り出して、フィールドの値だけをDataFrameに整形しています。


✅ まとめ

  • kintoneのAPIは100件ずつしか取得できないため、ループが必要
  • 各レコードはフィールドコードをキーとした辞書型で返ってくる
  • PythonとPandasを使えば、kintoneのデータを簡単に加工・分析できる!

📢 最後に

このように、kintoneのデータもPythonで柔軟に扱えます!
これからkintone + Pythonで業務効率化を図りたい人の参考になれば嬉しいです 🙌

Qiitaへの「いいね」やコメントも励みになります。ありがとうございました!

1
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
1
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?