2
2

More than 5 years have passed since last update.

PythonでRESTを叩きNew Relicからデータを取得する

Posted at

こんにちは。

Pythonのrequestsライブラリを使ってRESTクライアントを作成し、New Relicから情報を取り出すスクリプト例です。
と言っても、一般的なRESTクライアントなので参考になる方は少ないかもしれません。。

1. 必要なもの

  • python実行環境(筆者の環境は2.7.12)
[ec2-user@xxx ~]$ python --version
Python 2.7.12
  • pythonのrequestsライブラリ(以下コマンドでインストール)
[ec2-user@xxx ~]$ pip install requests
  • New Relicで監視しているなにか(今回はPythonアプリケーション)

2. サンプルコード

エラーハンドリング等諸々端折っていますので、適宜必要に応じ追加してください。

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import requests

# def getAppInfo( sApiKey, sAppID ):
def getAppInfo( sApiKey ):

    sURL = "https://api.newrelic.com/v2/applications.json"
    sHeaders = { 'X-Api-Key': sApiKey }

    stRes = requests.get( sURL, headers=sHeaders )
    # stData = stRes.json()

    return stRes


if __name__ == '__main__':

    sApiKey = "{API Key}"
    # sAppID = "{Application ID}"

    # stRes = getAppInfo( sApiKey, sAppID )
    stRes = getAppInfo( sApiKey )

    print stRes.text

3. 実行結果

requestsのgetメソッドの実行結果のテキストをそのまま出しているだけの単純なつくりのため、mjson.toolで整形して表示させています。

apm_gray_status.png

{
    "applications": [
        {
            "health_status": "gray",
            "id": 12345678,
            "language": "python",
                  中略
            "name": "Python Agent Test",
            "reporting": false,
            "settings": {
                "app_apdex_threshold": 0.5,
                "enable_real_user_monitoring": true,
                "end_user_apdex_threshold": 7.0,
                "use_server_side_config": false
            }
        }
    ],
    "links": {
        中略
    }
}

1つしかアプリケーションがなく状態もヘルシーでない(gray)のであまりいい例ではないですが、アプリケーションの情報を取得できていることがわかります。
他のNew Relic APIもこれの応用で同じように叩くことができます。

なお、このようなライブラリもあるようで、より楽にRESTクライアントの実装ができそうです。この辺りも試したら記事にしたいと思います。

それでは。

2
2
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
2
2