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/dns_records \
  -H "Authorization: Bearer 1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Content-Type: application/json" \
  -d '{"type": "A", "name": "example.com", "content": "192.0.2.1", "ttl": 300}'

Python · requests

import os
import requests

zone_id = os.environ["ZONE_ID"]
headers = {
    "Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "type": "A",
    "name": "example.com",
    "content": "192.0.2.1",
    "ttl": 300
}

response = requests.post(
    f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records",
    headers=headers,
    json=data
)

response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

zone_id = os.environ["ZONE_ID"]
headers = {
    "Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
    "Content-Type": "application/json"
}
data = {
    "type": "A",
    "name": "example.com",
    "content": "192.0.2.1",
    "ttl": 300
}

with httpx.Client() as client:
    response = client.post(
        f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records",
        headers=headers,
        json=data
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'node:process';

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

const headers = {
  'Authorization': `Bearer ${apiToken}`,
  'Content-Type': 'application/json'
};

const data = {
  type: 'A',
  name: 'example.com',
  content: '192.0.2.1',
  ttl: 300
};

const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}/dns_records`, {
  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);

Node.js · axios

import axios from 'axios';
import { env } from 'node:process';

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

const headers = {
  'Authorization': `Bearer ${apiToken}`,
  'Content-Type': 'application/json'
};

const data = {
  type: 'A',
  name: 'example.com',
  content: '192.0.2.1',
  ttl: 300
};

try {
  const response = await axios.post(
    `https://api.cloudflare.com/client/v4/zones/${zoneId}/dns_records`,
    data,
    { headers }
  );
  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"
	"io"
	"log"
	"net/http"
	"os"
)

type DNSRecord struct {
	Type    string `json:"type"`
	Name    string `json:"name"`
	Content string `json:"content"`
	TTL     int    `json:"ttl"`
}

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

	data := DNSRecord{
		Type:    "A",
		Name:    "example.com",
		Content: "192.0.2.1",
		TTL:     300,
	}

	body, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest(
		"POST",
		fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records", zoneID),
		bytes.NewBuffer(body),
	)
	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("HTTP error! status: %s, body: %s", resp.Status, body)
	}

	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');
$apiToken = getenv('CF_API_TOKEN');

$data = [
    'type' => 'A',
    'name' => 'example.com',
    'content' => '192.0.2.1',
    'ttl' => 300
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/{$zoneId}/dns_records");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $apiToken,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    die("HTTP error! status: {$httpCode}, body: {$response}");
}

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

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}/dns_records")
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 = {
  type: 'A',
  name: 'example.com',
  content: '192.0.2.1',
  ttl: 300
}.to_json

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{response.code}, body: #{response.body}"
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 + "/dns_records")!
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] = [
    "type": "A",
    "name": "example.com",
    "content": "192.0.2.1",
    "ttl": 300
]

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 else {
        print("Invalid response")
        return
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \(httpResponse.statusCode)")
        if let data = data, let body = String(data: data, encoding: .utf8) {
            print("Body: \(body)")
        }
        return
    }
    if let data = data {
        do {
            let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
            print(json ?? "")
        } catch {
            print("JSON parsing error: \(error)")
        }
    }
}
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 client = Client::new();
    let url = format!(
        "https://api.cloudflare.com/client/v4/zones/{}/dns_records",
        zone_id
    );

    let body = json!({
        "type": "A",
        "name": "example.com",
        "content": "192.0.2.1",
        "ttl": 300
    });

    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", api_token))
        .header("Content-Type", "application/json")
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        eprintln!(
            "HTTP error! status: {}",
            response.status()
        );
        let body = response.text()?;
        eprintln!("Body: {}", body);
        return Err("Request failed".into());
    }

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

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

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var body = new
        {
            type = "A",
            name = "example.com",
            content = "192.0.2.1",
            ttl = 300
        };

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

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            var errorBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"HTTP error! status: {response.StatusCode}, body: {errorBody}");
            return;
        }

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

Translation notes

  • All implementations read secrets from environment variables (ZONE_ID, CF_API_TOKEN).
  • Python uses requests/httpx, Node.js uses fetch/axios, Go uses net/http, PHP uses cURL, Ruby uses Net::HTTP, Swift uses URLSession, Rust uses reqwest, C# uses HttpClient.
  • JSON bodies are constructed as objects/dicts, not raw strings.
  • Error handling checks HTTP status and reads response body on failure.
  • Bearer token is redacted in parsed output.

Common pitfalls when porting

  • Forgetting to set Content-Type header in raw HTTP clients.
  • Not handling HTTPS properly in languages like Go or Ruby without explicit SSL configuration.
  • Assuming synchronous HTTP clients are always available (e.g., Swift's URLSession is async).
  • Not properly escaping environment variable values in URL construction (e.g., Go's fmt.Sprintf is safe here).
  • Ignoring SSL certificate validation in production (not shown here for brevity).

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 separate configuration from code, reducing the risk of secret leakage in version control or logs. They also allow different deployments to use different credentials without code changes.

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or pagination helpers. For example, in Python's requests, use response.iter_content() for large files. In Go, use io.Copy() with the response body.

Can I use async/await in all languages?

Most modern languages support async/await (Python, Node.js, Swift, Rust, C#). For others (Go, PHP, Ruby), use their native concurrency models (goroutines, fibers, etc.).

What if the API requires a custom CA certificate?

In Go, use http.Client with a custom TLS config. In Python, use requests with verify='/path/to/cert.pem'. In Node.js, use https.Agent with ca option. In C#, use HttpClientHandler with ServerCertificateCustomValidationCallback.