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?

More than 3 years have passed since last update.

MetabaseにREST APIを使ってアクセスしSQLを実行する

Last updated at Posted at 2020-10-10

やりたいこと

Metabase(REST API 経由)で、SQL を実行する。

やること

  • username, password を使って、セッションID を取得する。
  • セッションID を使い、Metadase にアクセスして、SQL を実行する。

参考ドキュメント

The Metabase API only supports JSON; all responses are returned as JSON, and request bodies must be JSON. As such, you'll want to pass the Content-Type: application/json header with all of your requests.

手順

セッションID の取得

_USERNAME_='<username>'
_PASSWORD_='<password>'
_METABSE_URL_='<url>'

curl -X POST \
  -H "Content-Type: application/json" \
  -d "{\"username\": \"${_USERNAME_}\", \"password\": \"${_PASSWORD_}\" }" \
  https://${_METABSE_URL_}/api/session

↑を実行すると、↓のようなセッションIDが取得できます。

{"id":"6ce27067-23a4-4d2f-beeb-80ef31e034a9"}

セッションに関する注意点

Sessions are good for 14 days by default; you can configure this value by setting the env var MAX_SESSION_AGE (value is in minutes).

セッションはデフォルトで 14日間有効。環境変数の MAX_SESSION_AGE(秒単位)で指定可能。

Logins are rate-limited for security purposes. Thus you should cache the credentials you receive and reuse them until they expire.

セッションは期限が切れるまで使い回すこと。

If a session is expired or otherwise no longer valid, the API will return a response with a 401 (Unauthorized) status code.

セッションが切れた場合、API は 401(Unauthorized)を返す。

We recommend writing your code in a way will fetch a new session token and automatically retry requests a single time when the API returns a 401.

401 が返された時は、セッションを再取得して一度リトライすることを推奨する。

Metabase で SQL を実行する

↑で取得したセッションIDを使って REST API 経由で SQL を実行します。

_SESSION_ID_=<session_id>
_METABASE_URL_=<url>

curl -X POST \
  ${_MTABASE_URL_}/api/dataset \
  -H "Content-Type: application/json" \
  -H "X-Metabase-Session: ${_SESSION_ID_}" \
  -d '{
  "database": 4, // database の番号を指定する。Metabase の GUI で確認可能。
  "native": {
    "query": "SELECT COUNT(*) FROM foo"
  },
  "type": "native"
}'

レスポンスは、data.rows の中に配列で入っています。

{"data":{"rows":[
[43]
],
...

参考:https://stackoverflow.com/questions/50620095/is-it-possible-to-get-raw-data-from-a-metabase-mbql-sql-query-via-the-rest-api

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?