Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST api.cloudflare.com · body: json · secrets replaced with env vars.

Source cURL
curl -X POST https://api.cloudflare.com/client/v4/zones/1234567890/analytics/dashboard \
  -H "Authorization: Bearer 1234567890abcdef1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{"since":"2023-01-01T00:00:00Z","until":"2023-01-02T00:00:00Z"}'

Python · requests

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())

Python · httpx

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())

Node.js · fetch

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));

Node.js · axios

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);
  });

Go · net/http

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 · cURL

<?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);

Ruby · net/http

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)

Swift · URLSession

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()

Rust · reqwest

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(())
}

C# · HttpClient

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);
    }
}

Translation notes

  • All implementations read secrets from environment variables (ZONE_ID, CF_API_TOKEN)
  • Python requests and httpx use json parameter for automatic serialization
  • Go uses a struct for request body and bytes.Buffer for the request
  • PHP uses stream_context_create for simplicity
  • Ruby uses Net::HTTP with JSON serialization
  • Swift uses URLSession with JSONSerialization
  • Rust uses reqwest blocking client and serde_json for JSON handling
  • C# uses HttpClient with System.Text.Json for serialization

Common pitfalls when porting

  • Forgetting to set ZONE_ID and CF_API_TOKEN environment variables
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • In Go, forgetting to close the response body
  • In Swift, not running the RunLoop to execute async tasks
  • In Rust, using async reqwest without a runtime in a blocking context
  • In PHP, not checking for false return from file_get_contents

About cURL → code translation

cURL is the lingua franca of API documentation: every vendor docs page ships a cURL snippet you can paste into a terminal and immediately see the API working. Translating that into your actual application code shouldn't be a 20-minute Stack-Overflow safari, but without a good translator it usually is.

Qaynaq Labs' cURL → code tool reads the full command — method, URL, headers, query params, body type, and auth — and emits idiomatic client code in 10 languages. Authentication goes through environment variables by default, request bodies become language-native data structures (not raw JSON strings), and minimal error handling is included.

Frequently asked

Why use environment variables for secrets instead of hardcoding?

Environment variables are the standard way to handle secrets in applications. They prevent secrets from being committed to version control and allow for different configurations across environments.

Can I use async/await in Go or Rust for this request?

Yes, but the provided examples use blocking clients for simplicity. Both Go and Rust have async HTTP clients (e.g., reqwest async in Rust, net/http with goroutines in Go) that can be used for non-blocking requests.