Creating an analytics token for R2 analytics

I would like to retrieve analytics information from GraphQL.

My code is working fine when using the global account API key and I get data back, but when I switch to use an API token, this results in an error:

array(2) {
  ["data"] => NULL
  ["errors"] => array(1) {
    [0] => array(3) {
      ["message"] => string(31) "not authorized for that account"
      ["path"] => NULL
      ["extensions"] => array(2) {
        ["code"] => string(5) "authz"
        ["timestamp"] => string(30) "2024-02-02T14:20:19.176988532Z"
      }
    }
  }
}

Successful code:

$response = $app->http()->client()->post('https://api.cloudflare.com/client/v4/graphql/', [
	'headers' => [
		'X-Auth-Email' => '[email protected]',
		'X-Auth-Key' => $authKey,
//		'Authorization' => 'Bearer ' . $apiToken,
		'Content-Type' => 'application/json',
	],
	'json' => $params,
]);

Unsuccessful code:

$response = $app->http()->client()->post('https://api.cloudflare.com/client/v4/graphql/', [
	'headers' => [
//		'X-Auth-Email' => '[email protected]',
//		'X-Auth-Key' => $authKey,
		'Authorization' => 'Bearer ' . $apiToken,
		'Content-Type' => 'application/json',
	],
	'json' => $params,
]);

The GraphQL query in both cases:

query {
  viewer {
    accounts(filter: {accountTag: $accountTag}) {
      r2OperationsAdaptiveGroups(limit: 10000, filter: $filter) {
        sum {
          requests
        }
      }
    }
  }
}

Any guidance much appreciated!

You should only be using 1 auth method. Either X-Auth-Email and X-Auth-Key or Authorization

What are the permissions for the API token?

I am - in each of the examples one of the methods is commented out with //

As per the documentation it has the Analytics permission.

To confirm, Account Analytics and you haven’t limited to a different account than you are trying to use.

This helps. Thank you.

I was using Zone.Analytics which seemed to be correct based on the guide I was reading but I understand now that was incorrect.

Account.Account Analytics is the correct one for the query I was writing.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.