0
0

More than 3 years have passed since last update.

CloudflareでGraphQLを使った話

Last updated at Posted at 2020-06-07

経緯

Cloudflareを使っていると帯域幅が気になる事はよくあると思う。
APIを利用すると便利だけど、古いAPIはそろそろ使えなくなるらしい。

https://api.cloudflare.com/#zone-analytics-dashboard
Deprecation Warning
End of life Date: 2020年11月2日
Please use the new GraphQL Analytics API instead: https://developers.cloudflare.com/analytics/graphql-api/.

GraphQLなど聞いた事も無いが移行するしか無い。説明を見ながらテスト。
https://developers.cloudflare.com/analytics/migration-guides/zone-analytics/
https://developers.cloudflare.com/analytics/graphql-api/tutorials/build-your-own-analytics/

結果

日毎の帯域幅まとめは以下のようにすると取得できた。

CloudflareGraphQL.php
<?php
$authemail="username@example.com";  //アカウントのメールアドレス
$apikey="0123456789abcdef0123456789abcdef01234";  //APIキー
$zoneid="0123456789abcdef0123456789abcdef";  //ゾーンID

$datetime_geq = gmdate('Y-m-d', strtotime("-364 days")); //開始日
$datetime_lt = gmdate('Y-m-d', strtotime("now")); //終了日
$content = '{
  viewer {
    zones(filter: {zoneTag: "'.$zoneid.'"}) {
      httpRequests1dGroups(orderBy: [date_ASC], limit: 365,
        filter: {date_geq: "'.$datetime_geq.'", date_lt: "'.$datetime_lt.'"}){
        dimensions {
          date
        }
        sum {
          bytes
        }
      }
    }
  }
}';
$url = 'https://api.cloudflare.com/client/v4/graphql';
$ch = curl_init();
$defaultOptions = [
    CURLOPT_URL => $url,
    CURLOPT_POST => true, //GraphQLはPOST必須らしい
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => json_encode(array('query' => $content)),
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
        "X-AUTH-EMAIL: ".$authemail,
        "X-AUTH-KEY: ".$apikey,
    ]
];
curl_setopt_array($ch, $defaultOptions);
$chContents = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
curl_close($ch);
echo $chContents; //応答はJSONなのでjson_decodeでデコードして利用する

沢山オプションを付けるとタイムアウトする事があるので、期間を短くするとか配慮が必要。

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