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/0da42c8d2132a9ddaf714f9e7c920711/purge_cache \
  --header "Authorization: Bearer 1234567890abcdef1234567890abcdef1234567890" \
  --header "Content-Type: application/json" \
  --data '{"purge_everything":true}'

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}/purge_cache"
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.get("ZONE_ID")
auth_token = os.environ.get("CF_API_TOKEN")

url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache"
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

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}/purge_cache`;
const headers = {
  'Authorization': `Bearer ${authToken}`,
  'Content-Type': 'application/json'
};
const data = { purge_everything: true };

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  })
  .then(console.log)
  .catch(console.error);

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}/purge_cache`;
const headers = {
  'Authorization': `Bearer ${authToken}`,
  'Content-Type': 'application/json'
};
const data = { purge_everything: true };

axios.post(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Go · net/http

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"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/purge_cache", zoneId)
	requestBody, _ := json.Marshal(PurgeRequest{PurgeEverything: true})

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
	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()

	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("Request failed with status: %s, body: %s", resp.Status, string(body))
	}

	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}/purge_cache";
$data = ['purge_everything' => true];

$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 ($response === false) {
    throw new Exception("Request failed");
}

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

Ruby · net/http

require 'net/http'
require 'json'
require 'uri'

zone_id = ENV.fetch('ZONE_ID')
auth_token = ENV.fetch('CF_API_TOKEN')

uri = URI.parse("https://api.cloudflare.com/client/v4/zones/#{zone_id}/purge_cache")
request = Net::HTTP::Post.new(uri.path, {
  'Authorization' => "Bearer #{auth_token}",
  'Content-Type' => 'application/json'
})
request.body = { purge_everything: true }.to_json

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP request failed: #{response.code} #{response.message}"
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 + "/purge_cache")!
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("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("Request failed")
        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 the async task to complete
RunLoop.main.run()

Rust · reqwest

use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

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/{}/purge_cache", zone_id);
    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        header::HeaderValue::from_str(&format!("Bearer {}", auth_token))?,
    );
    headers.insert(
        "Content-Type",
        header::HeaderValue::from_static("application/json"),
    );

    let body: HashMap<&str, bool> = HashMap::from([("purge_everything", true)]);

    let client = Client::new();
    let response = client
        .post(&url)
        .headers(headers)
        .json(&body)
        .send()?;

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

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

    Ok(())
}

C# · HttpClient

using System;
using System.Collections.Generic;
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 client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, $"https://api.cloudflare.com/client/v4/zones/{zoneId}/purge_cache");

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
        request.Content = new StringContent(JsonSerializer.Serialize(new { purge_everything = true }));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine("Request failed");
            return;
        }

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

Translation notes

  • All implementations use environment variables for secrets (ZONE_ID, CF_API_TOKEN)
  • Python requests and httpx use .json() for automatic JSON serialization
  • Go uses a struct for the request body for type safety
  • Ruby uses Net::HTTP which is the standard library for HTTP requests
  • Swift uses URLSession for async networking
  • Rust uses reqwest blocking client for simplicity in the example
  • C# uses HttpClient with async/await for modern .NET practices
  • Error handling is minimal but checks HTTP status codes and raises exceptions where appropriate

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Not handling SSL/TLS verification in Go or other low-level clients
  • Assuming synchronous behavior in Swift or Rust without proper async handling
  • Mismatching Content-Type headers (e.g., sending JSON without setting the header)
  • Not properly escaping or validating environment variable values
  • Ignoring HTTP status codes in error handling

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, reducing the risk of accidental exposure in version control or logs. They also allow different configurations across environments (dev, staging, prod) without code changes.

How do I handle pagination or large responses in these clients?

Most HTTP clients provide streaming or chunked response handling. For example, in Python requests you can use `response.iter_content()`, in Go use `io.ReadAll()` with buffering, and in Node.js use streams. Check the library's documentation for pagination-specific helpers.

Can I use async/await in Python requests?

No, the standard `requests` library is synchronous. For async HTTP in Python, use `httpx` or `aiohttp`. The `requests` library is simpler but blocks the event loop.