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/zone1234567890/cache/purge \
  -H "Authorization: Bearer 1234567890abcdef1234567890abcdef" \
  -H "Content-Type: application/json" \
  -d '{"purge_everything":true}'

Python · requests

import os
import requests

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

url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/purge"
headers = {
    "Authorization": f"Bearer {auth_token}",
    "Content-Type": "application/json"
}
data = {"purge_everything": True}

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["ZONE_ID"]
auth_token = os.environ["CF_API_TOKEN"]

url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/purge"
headers = {
    "Authorization": f"Bearer {auth_token}",
    "Content-Type": "application/json"
}
data = {"purge_everything": True}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import process from 'process';

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

const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/cache/purge`;
const headers = {
  'Authorization': `Bearer ${authToken}`,
  'Content-Type': 'application/json'
};
const data = { purge_everything: true };

try {
  const response = await fetch(url, {
    method: 'POST',
    headers,
    body: JSON.stringify(data)
  });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  const json = await response.json();
  console.log(json);
} catch (error) {
  console.error('Request failed:', error);
}

Node.js · axios

import axios from 'axios';
import process from 'process';

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

const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/cache/purge`;
const headers = {
  'Authorization': `Bearer ${authToken}`,
  'Content-Type': 'application/json'
};
const data = { purge_everything: true };

try {
  const response = await axios.post(url, data, { headers });
  console.log(response.data);
} catch (error) {
  if (error.response) {
    console.error('Request failed:', error.response.status, error.response.data);
  } else {
    console.error('Request failed:', error.message);
  }
}

Go · net/http

package main

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

type PurgeRequest struct {
	PurgeEverything bool `json:"purge_everything"`
}

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

	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/cache/purge", zoneId)
	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+authToken)
	req.Header.Set("Content-Type", "application/json")

	data := PurgeRequest{PurgeEverything: true}
	body, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}
	req.Body = http.NoBody
	req.GetBody = func() (io.ReadCloser, error) {
		return io.NopCloser(bytes.NewReader(body)), nil
	}

	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: %s", resp.Status)
	}

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

PHP · cURL

<?php

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

$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/cache/purge";
$data = ['purge_everything' => true];

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

$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}/cache/purge")
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 = { purge_everything: true }.to_json

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed with 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 + "/cache/purge")!
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] = ["purge_everything": true]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Request failed: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("Request failed with 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()

// Keep the program running to allow async task to complete
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/{}/cache/purge", zone_id);
    let client = Client::new();
    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", auth_token))
        .header("Content-Type", "application/json")
        .json(&json!({"purge_everything": true}))
        .send()?;

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

    let body = response.json::<serde_json::Value>()?;
    println!("{}", body);
    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()
    {
        var zoneId = Environment.GetEnvironmentVariable("ZONE_ID");
        var authToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");

        var url = $"https://api.cloudflare.com/client/v4/zones/{zoneId}/cache/purge";
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var data = new { purge_everything = true };
        var response = await client.PostAsJsonAsync(url, data);

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed with status: {response.StatusCode}");
        }

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

Translation notes

  • All implementations read secrets from environment variables (ZONE_ID, CF_API_TOKEN).
  • Python httpx uses a client context for connection pooling.
  • Go implementation uses http.NoBody with GetBody to allow retries with the same body.
  • Swift uses async URLSession but requires RunLoop to keep the program alive for demonstration.
  • Rust uses reqwest blocking client for simplicity; async version would require a runtime like tokio.
  • C# uses HttpClient with PostAsJsonAsync for automatic JSON serialization.

Common pitfalls when porting

  • Forgetting to set Content-Type header in raw HTTP clients (e.g., Go, Ruby).
  • Not handling HTTP errors properly (e.g., checking status codes).
  • In Go, not properly resetting the request body for retries can cause issues.
  • In Swift, forgetting to keep the program alive when using async URLSession.
  • In Rust, using async reqwest without a runtime will cause compilation errors.

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, avoiding accidental exposure in source code or version control. 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 `http.Client` with `Response.Body` as an `io.Reader`, and in Rust `reqwest` with `response.bytes_stream()`.

Can I use async/await in all languages?

Most modern languages support async/await, but some (like Python httpx, Node.js, Rust with tokio) have better support. In Go, concurrency is handled via goroutines, and in Swift, URLSession has async/await support in newer versions.