Call GraphQL from HomeAssistant
I wanted to call Cloudflare’s GraphQL endpoint from HomeAssistant in order to get some stats about caching, blocked requests, etc. You just call it as a normal REST sensor.
As part of the payload you have to send through a datetime and the zone_id of your site; this proved to be a bit of an issue and does not seem to be well documented anywhere.
The below steps will outline how to accomplish the above.
Step 1: Create template sensors for Zone_ID and datetime
template:
- sensor:
- name: "Zone Tag"
state: !secret graphql_cloudflare_zone_mysite
- name: "Timestamp 23 Hours Ago"
state: "{{ (now() - timedelta(hours=23)) | as_timestamp | timestamp_custom('%Y-%m-%dT%H:%M:%SZ') }}"
These 2 sensors hold the following data:
- Zone Tag: Just the Zone ID
- Timestamp 23 Hours Ago: The current date and time, minus 23 hours. Because I am on the free Cloudflare plan, I can only query 24 hours of history. 23 hours is therefore a safe bet.
Creating these variables will keep our payload much simpler. We essentially use them as global variables.
Step 2: Create the REST sensor for the GraphQL call
rest:
- resource: !secret graphql_cloudflare_url
scan_interval: 300
method: POST
headers:
Content-Type: "application/json"
Authorization: !secret graphql_cloudflare_bearer
payload_template: >
{
"query": "{ viewer { zones(filter: { zoneTag: \"{{ states('sensor.zone_tag') }}\" }) { httpRequestsAdaptiveGroups( limit: 10 filter: { datetime_geq: \"{{ states('sensor.timestamp_23_hours_ago') }}\" } ) { count dimensions { securityAction } } } } }"
}
sensor:
- name: "Normal Requests Count"
value_template: >
{{
value_json
}}
The 2 pieces of text highlighted in red is where we are using the Template Sensors.
Step 3: Troubleshooting (Use value_template (purple text))
I could not figure out why I got errors, so I figured out that by just putting “value_json” inside the value_template, HomeAssistant will show the entire response from Cloudflare.
Caveat
It seems that when HomeAssistant starts up after a restart, the template sensors are not populated yet, so the value for “Normal Requests Count” will be some error essentially saying that the “datetime_geq” is not formatted correctly. But, after “scan_interval” time has passed, everything works as it should.