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 cloudflare_api_token" -H "Content-Type: application/json" -d '{"files":["https://example.com/path/to/file.jpg"]}'

Python · requests

import os
import requests

zone_id = os.environ.get("ZONE_ID")
auth_token = os.environ.get("CLOUDFLARE_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 = {
    "files": ["https://example.com/path/to/file.jpg"]
}

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("CLOUDFLARE_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 = {
    "files": ["https://example.com/path/to/file.jpg"]
}

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.CLOUDFLARE_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 = {
  files: ['https://example.com/path/to/file.jpg']
};

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

Node.js · axios

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

const zoneId = process.env.ZONE_ID;
const authToken = process.env.CLOUDFLARE_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 = {
  files: ['https://example.com/path/to/file.jpg']
};

axios.post(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Error:', error.response.status, error.response.data);
    } else {
      console.error('Error:', error.message);
    }
  });

Go · net/http

package main

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

func main() {
	zoneID := os.Getenv("ZONE_ID")
	authToken := os.Getenv("CLOUDFLARE_API_TOKEN")

	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/purge_cache", zoneID)
	data := map[string]interface{}{
		"files": []string{"https://example.com/path/to/file.jpg"},
	}
	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	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("Unexpected status code: %d", resp.StatusCode)
	}

	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('CLOUDFLARE_API_TOKEN');

$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/purge_cache";
$data = [
    'files' => ['https://example.com/path/to/file.jpg']
];

$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['CLOUDFLARE_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 = { files: ['https://example.com/path/to/file.jpg'] }.to_json

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["CLOUDFLARE_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] = ["files": ["https://example.com/path/to/file.jpg"]]
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("Unexpected status code: \((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::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("CLOUDFLARE_API_TOKEN")?;

    let url = format!("https://api.cloudflare.com/client/v4/zones/{}/purge_cache", zone_id);
    let client = Client::new();

    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        format!("Bearer {}", auth_token).parse()?,
    );
    headers.insert("Content-Type", "application/json".parse()?);

    let body: HashMap<&str, Vec<&str>> = HashMap::from([
        ("files", vec!["https://example.com/path/to/file.jpg"]),
    ]);

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

    if !response.status().is_success() {
        return Err(format!("Request failed: {}", response.status()).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("CLOUDFLARE_API_TOKEN");

        var client = new HttpClient();
        var url = $"https://api.cloudflare.com/client/v4/zones/{zoneId}/purge_cache";

        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 Dictionary<string, object>
        {
            { "files", new List<string> { "https://example.com/path/to/file.jpg" } }
        };

        request.Content = new StringContent(JsonSerializer.Serialize(body));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();

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

Translation notes

  • Python: Both `requests` and `httpx` are idiomatic; `requests` is synchronous, `httpx` supports async.
  • Node.js: `fetch` is native in modern environments; `axios` is a popular third-party library.
  • Go: Uses standard library `net/http`; requires manual JSON marshaling.
  • PHP: Uses `file_get_contents` with stream context for simplicity.
  • Ruby: Uses `net/http` from the standard library.
  • Swift: Uses `URLSession` with async/await pattern (requires iOS 15+/macOS 12+).
  • Rust: Uses `reqwest` blocking client for simplicity; async version would use `reqwest::Client`.
  • C#: Uses `HttpClient` with async/await; requires .NET Core 3.1+ or .NET 5+.

Common pitfalls when porting

  • Forgetting to set `ZONE_ID` or `CLOUDFLARE_API_TOKEN` environment variables.
  • Not handling HTTP errors (e.g., 4xx/5xx responses) in production code.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, `RunLoop.main.run()` is required for synchronous execution in CLI apps.
  • In Rust, the blocking client may not be suitable for high-throughput applications.
  • In C#, `HttpClient` should ideally be reused (not recreated per request) for performance.

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 (e.g., in version control). They also allow dynamic configuration across environments (dev, staging, prod).

How do I make the request asynchronous in Python?

For `requests`, use `asyncio` with `aiohttp` or `httpx` in async mode. Example with `httpx`: ```python import httpx import asyncio async def purge_cache(): async with httpx.AsyncClient() as client: response = await client.post(url, headers=headers, json=data) response.raise_for_status() asyncio.run(purge_cache()) ```

Can I use a proxy with these clients?

Yes. Most clients support proxy configuration: - Python `requests`: `proxies={'http': '...', 'https': '...'}` - Node.js `axios`: `axios.create({ proxy: '...' })` - Go: `http.ProxyFromEnvironment` or custom proxy - C#: `HttpClient` with `WebProxy` Check the library's documentation for proxy-specific syntax.