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/purge_cache \
  -H "Authorization: Bearer 1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Content-Type: application/json" \
  -d '{"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

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

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('Error:', err));

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}/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:', 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/purge_cache", 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")

	body := PurgeRequest{PurgeEverything: true}
	jsonBody, _ := json.Marshal(body)
	req.Body = http.NoBody
	req.GetBody = func() (io.ReadCloser, error) {
		return io.NopCloser(bytes.NewReader(jsonBody)), 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("unexpected status code: %d", resp.StatusCode)
	}

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
}

PHP · cURL

<?php

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

$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/purge_cache";
$headers = [
    'Authorization: Bearer ' . $authToken,
    'Content-Type: application/json'
];
$data = json_encode(['purge_everything' => true]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    die("HTTP error: {$httpCode}");
}

$decoded = json_decode($response, true);
print_r($decoded);
curl_close($ch);

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")
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 "HTTP error: #{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 + "/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("HTTP error: \((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 reqwest::blocking::Client;
use serde_json::json;
use std::env;

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 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!("HTTP error: {}", 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}/purge_cache";
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

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

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error: {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 context manager for the client.
  • Go uses io.NopCloser for the request body due to httpx limitations.
  • Swift uses URLSession with async/await pattern.
  • Rust uses reqwest blocking client for simplicity.
  • C# uses HttpClient with PostAsJsonAsync for JSON serialization.

Common pitfalls when porting

  • Forgetting to set ZONE_ID or CF_API_TOKEN environment variables will cause runtime errors.
  • In Go, the request body handling is non-trivial due to http.Request limitations.
  • In Swift, the URLSession task runs asynchronously; ensure the RunLoop is active.
  • In Rust, the blocking client may block the main thread; consider async alternatives for production.
  • In PHP, curl_setopt must be set correctly for POST requests with JSON bodies.

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 prevent secrets from being committed to version control and allow configuration without code changes.

Can I use async/await in Python httpx?

Yes, replace the context manager with async/await and use httpx.AsyncClient.

How do I handle pagination or large responses in Go?

Use io.LimitReader to cap response sizes or stream responses with http.Client.