import os
import requests
zone_id = os.environ.get("ZONE_ID")
auth_token = os.environ.get("CF_API_TOKEN")
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/analytics/dashboard"
headers = {
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/json"
}
data = {
"since": "2023-01-01T00:00:00Z",
"until": "2023-01-02T00:00:00Z"
}
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import os
import httpx
zone_id = os.environ.get("ZONE_ID")
auth_token = os.environ.get("CF_API_TOKEN")
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/analytics/dashboard"
headers = {
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/json"
}
data = {
"since": "2023-01-01T00:00:00Z",
"until": "2023-01-02T00:00:00Z"
}
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
const fetch = require('node-fetch');
const zoneId = process.env.ZONE_ID;
const authToken = process.env.CF_API_TOKEN;
const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/analytics/dashboard`;
const headers = {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
};
const body = JSON.stringify({
since: '2023-01-01T00:00:00Z',
until: '2023-01-02T00:00:00Z'
});
fetch(url, {
method: 'POST',
headers,
body
})
.then(res => {
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
const axios = require('axios');
const zoneId = process.env.ZONE_ID;
const authToken = process.env.CF_API_TOKEN;
const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/analytics/dashboard`;
const headers = {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
};
const data = {
since: '2023-01-01T00:00:00Z',
until: '2023-01-02T00:00:00Z'
};
axios.post(url, data, { headers })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type RequestBody struct {
Since string `json:"since"`
Until string `json:"until"`
}
func main() {
zoneId := os.Getenv("ZONE_ID")
authToken := os.Getenv("CF_API_TOKEN")
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/analytics/dashboard", zoneId)
body := RequestBody{
Since: "2023-01-01T00:00:00Z",
Until: "2023-01-02T00:00:00Z",
}
jsonBody, err := json.Marshal(body)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+authToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
log.Fatalf("HTTP error! status: %s, body: %s", resp.Status, body)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
}
<?php
$zoneId = getenv('ZONE_ID');
$authToken = getenv('CF_API_TOKEN');
$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/analytics/dashboard";
$data = [
'since' => '2023-01-01T00:00:00Z',
'until' => '2023-01-02T00:00:00Z'
];
$options = [
'http' => [
'header' => [
"Authorization: Bearer {$authToken}",
"Content-Type: application/json"
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
throw new Exception("Request failed");
}
$response = json_decode($result, true);
print_r($response);
require 'net/http'
require 'json'
require 'uri'
zone_id = ENV['ZONE_ID']
auth_token = ENV['CF_API_TOKEN']
uri = URI.parse("https://api.cloudflare.com/client/v4/zones/#{zone_id}/analytics/dashboard")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{auth_token}"
request['Content-Type'] = 'application/json'
request.body = {
since: '2023-01-01T00:00:00Z',
until: '2023-01-02T00:00:00Z'
}.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error! status: #{response.code}"
end
puts JSON.parse(response.body)
import Foundation
let zoneId = ProcessInfo.processInfo.environment["ZONE_ID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["CF_API_TOKEN"] ?? ""
let url = URL(string: "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/analytics/dashboard")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + authToken, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: String] = [
"since": "2023-01-01T00:00:00Z",
"until": "2023-01-02T00:00:00Z"
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
return
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::env;
use reqwest::blocking::Client;
use serde_json::json;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let zone_id = env::var("ZONE_ID")?;
let auth_token = env::var("CF_API_TOKEN")?;
let url = format!(
"https://api.cloudflare.com/client/v4/zones/{}/analytics/dashboard",
zone_id
);
let client = Client::new();
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", auth_token))
.header("Content-Type", "application/json")
.json(&json!({
"since": "2023-01-01T00:00:00Z",
"until": "2023-01-02T00:00:00Z"
}))
.send()?;
if !response.status().is_success() {
return Err(format!("HTTP error! status: {}", response.status()).into());
}
let body = response.text()?;
println!("{}", body);
Ok(())
}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Text.Json;
class Program
{
static async Task Main()
{
var zoneId = Environment.GetEnvironmentVariable("ZONE_ID");
var authToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");
var url = $"https://api.cloudflare.com/client/v4/zones/{zoneId}/analytics/dashboard";
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var body = new {
since = "2023-01-01T00:00:00Z",
until = "2023-01-02T00:00:00Z"
};
request.Content = new StringContent(JsonSerializer.Serialize(body));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTTP error! status: {response.StatusCode}");
}
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}