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/accounts/account_id/workers/scripts/script_name/environments/production/secrets \
  -H "Authorization: Bearer abc123def456ghi789jkl012mno345pqr67890" \
  -H "Content-Type: application/json" \
  -d '{"name":"SECRET_KEY","text":"value123","type":"secret_text"}'

Python · requests

import os
import requests

response = requests.post(
    f"https://api.cloudflare.com/client/v4/accounts/{os.environ['ACCOUNT_ID']}/workers/scripts/{os.environ['SCRIPT_NAME']}/environments/production/secrets",
    headers={
        "Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
        "Content-Type": "application/json"
    },
    json={"name": "SECRET_KEY", "text": "value123", "type": "secret_text"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

async def main():
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"https://api.cloudflare.com/client/v4/accounts/{os.environ['ACCOUNT_ID']}/workers/scripts/{os.environ['SCRIPT_NAME']}/environments/production/secrets",
            headers={
                "Authorization": f"Bearer {os.environ['CF_API_TOKEN']}",
                "Content-Type": "application/json"
            },
            json={"name": "SECRET_KEY", "text": "value123", "type": "secret_text"}
        )
        response.raise_for_status()
        print(response.json())

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Node.js · fetch

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

(async () => {
  const response = await fetch(
    `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/workers/scripts/${env.SCRIPT_NAME}/environments/production/secrets`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${env.CF_API_TOKEN}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({"name": "SECRET_KEY", "text": "value123", "type": "secret_text"})
    }
  );
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  console.log(await response.json());
})();

Node.js · axios

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

(async () => {
  const response = await axios.post(
    `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/workers/scripts/${env.SCRIPT_NAME}/environments/production/secrets`,
    {"name": "SECRET_KEY", "text": "value123", "type": "secret_text"},
    {
      headers: {
        'Authorization': `Bearer ${env.CF_API_TOKEN}`,
        'Content-Type': 'application/json'
      }
    }
  );
  console.log(response.data);
})();

Go · net/http

package main

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

type Secret struct {
	Name string `json:"name"`
	Text string `json:"text"`
	Type string `json:"type"`
}

func main() {
	accountID := os.Getenv("ACCOUNT_ID")
	scriptName := os.Getenv("SCRIPT_NAME")
	apiToken := os.Getenv("CF_API_TOKEN")

	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/workers/scripts/%s/environments/production/secrets", accountID, scriptName)
	payload := Secret{Name: "SECRET_KEY", Text: "value123", Type: "secret_text"}
	payloadBytes, _ := json.Marshal(payload)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", 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 {
		log.Fatalf("HTTP error! status: %s", resp.Status)
	}

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

PHP · cURL

<?php

$accountId = getenv('ACCOUNT_ID');
$scriptName = getenv('SCRIPT_NAME');
$apiToken = getenv('CF_API_TOKEN');

$url = "https://api.cloudflare.com/client/v4/accounts/{$accountId}/workers/scripts/{$scriptName}/environments/production/secrets";
$data = [
    'name' => 'SECRET_KEY',
    'text' => 'value123',
    'type' => 'secret_text'
];

$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("HTTP request failed");
}

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

Ruby · net/http

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

account_id = ENV['ACCOUNT_ID']
script_name = ENV['SCRIPT_NAME']
api_token = ENV['CF_API_TOKEN']

uri = URI.parse("https://api.cloudflare.com/client/v4/accounts/#{account_id}/workers/scripts/#{script_name}/environments/production/secrets")
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 = { name: 'SECRET_KEY', text: 'value123', type: 'secret_text' }.to_json

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{response.code}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let accountId = ProcessInfo.processInfo.environment["ACCOUNT_ID"] ?? ""
let scriptName = ProcessInfo.processInfo.environment["SCRIPT_NAME"] ?? ""
let apiToken = ProcessInfo.processInfo.environment["CF_API_TOKEN"] ?? ""

let url = URL(string: "https://api.cloudflare.com/client/v4/accounts/" + accountId + "/workers/scripts/" + scriptName + "/environments/production/secrets")!
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] = [
    "name": "SECRET_KEY",
    "text": "value123",
    "type": "secret_text"
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    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;
use serde_json::json;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let account_id = env::var("ACCOUNT_ID")?;
    let script_name = env::var("SCRIPT_NAME")?;
    let api_token = env::var("CF_API_TOKEN")?;

    let url = format!(
        "https://api.cloudflare.com/client/v4/accounts/{}/workers/scripts/{}/environments/production/secrets",
        account_id, script_name
    );

    let client = reqwest::Client::new();
    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", api_token))
        .header("Content-Type", "application/json")
        .json(&json!({"name": "SECRET_KEY", "text": "value123", "type": "secret_text"}))
        .send()
        .await?;

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

    let body = response.json::<serde_json::Value>().await?;
    println!("{}", body);
    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        var accountId = Environment.GetEnvironmentVariable("ACCOUNT_ID");
        var scriptName = Environment.GetEnvironmentVariable("SCRIPT_NAME");
        var apiToken = Environment.GetEnvironmentVariable("CF_API_TOKEN");

        var url = $"https://api.cloudflare.com/client/v4/accounts/{accountId}/workers/scripts/{scriptName}/environments/production/secrets";
        var data = new { name = "SECRET_KEY", text = "value123", type = "secret_text" };

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await client.PostAsJsonAsync(url, data);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

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

Translation notes

  • All implementations use environment variables for secrets (ACCOUNT_ID, SCRIPT_NAME, CF_API_TOKEN)
  • Python httpx example is async; use sync version if needed
  • Go example uses standard library; consider using a more ergonomic HTTP client in production
  • Swift example uses URLSession; consider Combine or async/await for modern Swift
  • Rust example uses reqwest; add 'tokio' and 'serde_json' to Cargo.toml
  • C# example uses HttpClient; dispose properly in production code
  • All JSON bodies are constructed as objects, not raw strings

Common pitfalls when porting

  • Forgetting to set environment variables before running code
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Hardcoding secrets in source code or logs
  • Using deprecated HTTP clients in production (e.g., Python's urllib)
  • Not setting proper Content-Type headers for JSON requests
  • Ignoring SSL/TLS certificate validation in production environments

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 in Cloudflare API responses?

Cloudflare API responses include a 'result_info' object with 'count', 'total_count', and 'cursor' fields. Use the cursor value in subsequent requests to fetch the next page of results.

What's the difference between 'secret_text' and 'secret_blob' types?

'secret_text' is for plain text secrets, while 'secret_blob' is for binary data (e.g., certificates) encoded as base64. Choose the appropriate type based on your secret's format.