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/zone-id/activation -H "Authorization: Bearer 1234567890abcdef" -H "Content-Type: application/json" -d '{"name":"example.com"}'

Python · requests

import os
import requests

zone_id = os.environ["ZONE_ID"]
auth_token = os.environ["CF_API_TOKEN"]

response = requests.post(
    f"https://api.cloudflare.com/client/v4/zones/{zone_id}/activation",
    headers={
        "Authorization": f"Bearer {auth_token}",
        "Content-Type": "application/json"
    },
    json={"name": "example.com"}
)

if response.status_code != 200:
    raise Exception(f"Request failed with status {response.status_code}: {response.text}")

print(response.json())

Python · httpx

import os
import httpx

zone_id = os.environ["ZONE_ID"]
auth_token = os.environ["CF_API_TOKEN"]

async def activate_zone():
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"https://api.cloudflare.com/client/v4/zones/{zone_id}/activation",
            headers={
                "Authorization": f"Bearer {auth_token}",
                "Content-Type": "application/json"
            },
            json={"name": "example.com"}
        )
        response.raise_for_status()
        return response.json()

# For synchronous usage:
# with httpx.Client() as client:
#     response = client.post(...)
#     response.raise_for_status()

Node.js · fetch

const fetch = require('node-fetch');

const zoneId = process.env.ZONE_ID;
const authToken = process.env.CF_API_TOKEN;

(async () => {
  try {
    const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}/activation`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ name: 'example.com' })
    });

    if (!response.ok) {
      throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
})();

Node.js · axios

const axios = require('axios');

const zoneId = process.env.ZONE_ID;
const authToken = process.env.CF_API_TOKEN;

(async () => {
  try {
    const response = await axios.post(
      `https://api.cloudflare.com/client/v4/zones/${zoneId}/activation`,
      { name: 'example.com' },
      {
        headers: {
          'Authorization': `Bearer ${authToken}`,
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.status !== 200) {
      throw new Error(`Request failed with status ${response.status}: ${JSON.stringify(response.data)}`);
    }

    console.log(response.data);
  } catch (error) {
    console.error('Error:', error.message);
  }
})();

Go · net/http

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

type RequestBody struct {
	Name string `json:"name"`
}

func main() {
	zoneId := os.Getenv("ZONE_ID")
	authToken := os.Getenv("CF_API_TOKEN")

	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/activation", zoneId)
	body := RequestBody{Name: "example.com"}
	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 {
		log.Fatalf("Request failed with status %d: %s", resp.StatusCode, readBody(resp.Body))
	}

	var result map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	fmt.Println(result)
}

func readBody(body io.ReadCloser) string {
	data, _ := io.ReadAll(body)
	return string(data)
}

PHP · cURL

<?php

$zoneId = getenv('ZONE_ID');
$authToken = getenv('CF_API_TOKEN');

$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/activation";
$data = ['name' => 'example.com'];

$options = [
    'http' => [
        'header' => [
            "Authorization: Bearer {$authToken}",
            "Content-Type: application/json"
        ],
        'method' => 'POST',
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    throw new Exception("Request failed: " . $response);
}

$json = json_decode($response, true);
print_r($json);

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}/activation")
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 = { name: 'example.com' }.to_json

response = http.request(request)

unless response.code == '200'
  raise "Request failed with status #{response.code}: #{response.body}"
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"] ?? ""

guard let url = URL(string: "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/activation") else {
    fatalError("Invalid URL")
}

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = ["name": "example.com"]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("Error: \(error?.localizedDescription ?? "Unknown error")")
        return
    }

    if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
        print("Request failed with status \(httpResponse.statusCode): \(String(data: data, encoding: .utf8) ?? "")")
        return
    }

    if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

task.resume()

// For synchronous execution in a playground or test:
// let (data, response) = try await URLSession.shared.data(for: request)
// if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
//     let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
//     print(json)
// }

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 client = Client::new();
    let url = format!("https://api.cloudflare.com/client/v4/zones/{}/activation", zone_id);

    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", auth_token))
        .header("Content-Type", "application/json")
        .json(&json!({"name": "example.com"}))
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed with status {}: {}", response.status(), response.text()?).into());
    }

    let json: serde_json::Value = response.json()?;
    println!("{}", json);

    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var zoneId = Environment.GetEnvironmentVariable("ZONE_ID");
        var authToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");

        using var client = new HttpClient();
        client.BaseAddress = new Uri("https://api.cloudflare.com/client/v4/");

        var request = new HttpRequestMessage(HttpMethod.Post, $"zones/{zoneId}/activation");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
        request.Content = new StringContent(JsonSerializer.Serialize(new { name = "example.com" }), System.Text.Encoding.UTF8, "application/json");

        var response = await client.SendAsync(request);

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            throw new Exception($"Request failed with status {response.StatusCode}: {errorContent}");
        }

        var json = await response.Content.ReadAsStringAsync();
        Console.WriteLine(json);
    }
}

Translation notes

  • All implementations use environment variables for secrets (ZONE_ID, CF_API_TOKEN)
  • Python httpx example shows async usage; synchronous version is commented
  • Go example includes synchronous HTTP client usage
  • Swift example shows both async (URLSession.dataTask) and commented synchronous (URLSession.data) approaches
  • Rust example uses blocking reqwest client for simplicity
  • C# example uses System.Text.Json for JSON serialization
  • Error handling checks HTTP status code and reads response body on failure

Common pitfalls when porting

  • Forgetting to set ZONE_ID or CF_API_TOKEN environment variables
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • JSON serialization issues (e.g., using raw strings instead of proper JSON objects)
  • SSL/TLS verification issues in Go or other languages with custom HTTP clients
  • Timeout configurations not set in some libraries (may cause hangs)
  • Content-Type header must be explicitly set for JSON bodies in some libraries

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 instead of hardcoding secrets?

Environment variables separate configuration from code, preventing secrets from being committed to version control or exposed in logs. They also allow different configurations across environments (dev, staging, prod).

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or chunked response handling. For example, in Python requests you can use `response.iter_content()`, in Go `io.ReadAll(resp.Body)`, etc. Check the library's documentation for streaming support.

Can I use this with async/await in all languages?

Most modern languages support async/await. Python (httpx/asyncio), Node.js (fetch/axios), Swift (async/await), Rust (tokio), and C# (async Main) have native support. For others like Go, use goroutines or the async versions of the HTTP client.