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/firewall/rules \
  -H "Authorization: Bearer api_token_1234567890" \
  -H "Content-Type: application/json" \
  -d '{"mode":"challenge","configuration":{"target":"ip","value":"192.0.2.1"},"description":"Block suspicious IP"}'

Python · requests

import os
import requests

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

url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/firewall/rules"
headers = {
    "Authorization": f"Bearer {api_token}",
    "Content-Type": "application/json"
}
data = {
    "mode": "challenge",
    "configuration": {"target": "ip", "value": "192.0.2.1"},
    "description": "Block suspicious IP"
}

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

url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/firewall/rules"
headers = {
    "Authorization": f"Bearer {api_token}",
    "Content-Type": "application/json"
}
data = {
    "mode": "challenge",
    "configuration": {"target": "ip", "value": "192.0.2.1"},
    "description": "Block suspicious IP"
}

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 apiToken = process.env.CF_API_TOKEN;

const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/firewall/rules`;
const headers = {
  "Authorization": `Bearer ${apiToken}`,
  "Content-Type": "application/json"
};
const data = {
  mode: "challenge",
  configuration: { target: "ip", value: "192.0.2.1" },
  description: "Block suspicious IP"
};

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

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

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

const url = `https://api.cloudflare.com/client/v4/zones/${zoneId}/firewall/rules`;
const headers = {
  "Authorization": `Bearer ${apiToken}`,
  "Content-Type": "application/json"
};
const data = {
  mode: "challenge",
  configuration: { target: "ip", value: "192.0.2.1" },
  description: "Block suspicious IP"
};

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

Go · net/http

package main

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

type FirewallRule struct {
	Mode          string `json:"mode"`
	Configuration struct {
		Target string `json:"target"`
		Value  string `json:"value"`
	} `json:"configuration"`
	Description string `json:"description"`
}

func main() {
	zoneID := os.Getenv("ZONE_ID")
	apiToken := os.Getenv("CF_API_TOKEN")

	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/firewall/rules", zoneID)
	data := FirewallRule{
		Mode: "challenge",
		Configuration: struct {
			Target string `json:"target"`
			Value  string `json:"value"`
		}{
			Target: "ip",
			Value:  "192.0.2.1",
		},
		Description: "Block suspicious IP",
	}

	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 "+apiToken)
	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 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Request failed with status %d: %s", resp.StatusCode, string(body))
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(body))
}

PHP · cURL

<?php

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

$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/firewall/rules";
$data = [
    'mode' => 'challenge',
    'configuration' => [
        'target' => 'ip',
        'value' => '192.0.2.1'
    ],
    'description' => 'Block suspicious IP'
];

$options = [
    'http' => [
        'header' => [
            "Authorization: Bearer {$apiToken}",
            "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']
api_token = ENV['CF_API_TOKEN']

uri = URI.parse("https://api.cloudflare.com/client/v4/zones/#{zone_id}/firewall/rules")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{api_token}"
request['Content-Type'] = 'application/json'
request.body = {
  mode: 'challenge',
  configuration: { target: 'ip', value: '192.0.2.1' },
  description: 'Block suspicious IP'
}.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 apiToken = ProcessInfo.processInfo.environment["CF_API_TOKEN"] ?? ""

let url = URL(string: "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/firewall/rules")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + apiToken, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "mode": "challenge",
    "configuration": ["target": "ip", "value": "192.0.2.1"],
    "description": "Block suspicious IP"
]

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()

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 api_token = env::var("CF_API_TOKEN")?;

    let url = format!("https://api.cloudflare.com/client/v4/zones/{}/firewall/rules", zone_id);
    let client = Client::new();
    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", api_token))
        .header("Content-Type", "application/json")
        .json(&json!({
            "mode": "challenge",
            "configuration": {"target": "ip", "value": "192.0.2.1"},
            "description": "Block suspicious IP"
        }))
        .send()?;

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

    let body = response.text()?;
    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 apiToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");

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

        var data = new
        {
            mode = "challenge",
            configuration = new { target = "ip", value = "192.0.2.1" },
            description = "Block suspicious IP"
        };

        var response = await client.PostAsJsonAsync(url, data);
        response.EnsureSuccessStatusCode();
        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

public static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PostAsJsonAsync<T>(
        this HttpClient httpClient, string url, T data)
    {
        var content = new StringContent(JsonSerializer.Serialize(data), System.Text.Encoding.UTF8, "application/json");
        return await httpClient.PostAsync(url, content);
    }
}

Translation notes

  • All implementations read secrets from environment variables (ZONE_ID, CF_API_TOKEN)
  • Python requests and httpx use json parameter for automatic serialization
  • Go uses a struct for type-safe request body
  • PHP uses stream_context_create for simplicity
  • Ruby uses Net::HTTP with JSON serialization
  • Swift uses URLSession with async/await pattern
  • Rust uses reqwest blocking client for simplicity
  • C# uses HttpClient with PostAsJsonAsync extension for clean JSON handling

Common pitfalls when porting

  • Forgetting to set ZONE_ID or CF_API_TOKEN environment variables
  • Not handling HTTP errors (e.g., 4xx/5xx responses)
  • In Go, not properly closing response body with defer
  • In Swift, not running the RunLoop to execute async tasks
  • In Rust, using async reqwest without proper async runtime
  • In PHP, not checking for false return from file_get_contents

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 accidental exposure of secrets in version control or logs.

How do I handle pagination in Cloudflare API responses?

Check the 'result_info' field in the response for 'total_pages' and use the 'page' query parameter to iterate through pages.

What's the difference between requests and httpx in Python?

requests is synchronous and simpler, while httpx supports both sync and async I/O with a similar API.

Why does Go use a struct for the request body?

Structs provide compile-time type safety and make the code more maintainable than raw JSON strings.