Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST api.cloudflare.com · body: raw · secrets replaced with env vars.

Source cURL
curl -X POST https://api.cloudflare.com/client/v4/accounts/account_id/workers/scripts/script_name \
  -H "Authorization: Bearer 1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Content-Type: application/javascript" \
  -d 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })'

Python · requests

import os
import requests

account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"]
script_name = os.environ["CLOUDFLARE_SCRIPT_NAME"]
auth_token = os.environ["CLOUDFLARE_API_TOKEN"]

url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}"
headers = {
    "Authorization": f"Bearer {auth_token}",
    "Content-Type": "application/javascript"
}
body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })'

response = requests.post(url, headers=headers, data=body)
if response.status_code >= 400:
    print(f"Error: {response.status_code} - {response.text}")
else:
    print(response.text)

Python · httpx

import os
import httpx

account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"]
script_name = os.environ["CLOUDFLARE_SCRIPT_NAME"]
auth_token = os.environ["CLOUDFLARE_API_TOKEN"]

url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}"
headers = {
    "Authorization": f"Bearer {auth_token}",
    "Content-Type": "application/javascript"
}
body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })'

try:
    response = httpx.post(url, headers=headers, data=body)
    response.raise_for_status()
    print(response.text)
except httpx.HTTPStatusError as e:
    print(f"Error: {e.response.status_code} - {e.response.text}")

Node.js · fetch

const fetch = require('node-fetch');

const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
const scriptName = process.env.CLOUDFLARE_SCRIPT_NAME;
const authToken = process.env.CLOUDFLARE_API_TOKEN;

const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}`;
const headers = {
  'Authorization': `Bearer ${authToken}`,
  'Content-Type': 'application/javascript'
};
const body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })';

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

Node.js · axios

const axios = require('axios');

const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
const scriptName = process.env.CLOUDFLARE_SCRIPT_NAME;
const authToken = process.env.CLOUDFLARE_API_TOKEN;

const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}`;
const headers = {
  'Authorization': `Bearer ${authToken}`,
  'Content-Type': 'application/javascript'
};
const body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })';

axios.post(url, body, { headers })
  .then(response => {
    if (response.status >= 400) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    console.log(response.data);
  })
  .catch(error => console.error('Error:', error.message));

Go · net/http

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	accountId := os.Getenv("CLOUDFLARE_ACCOUNT_ID")
	scriptName := os.Getenv("CLOUDFLARE_SCRIPT_NAME")
	authToken := os.Getenv("CLOUDFLARE_API_TOKEN")

	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/workers/scripts/%s", accountId, scriptName)
	body := `addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })`

	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Authorization", "Bearer "+authToken)
	req.Header.Set("Content-Type", "application/javascript")
	req.Body = io.NopCloser(strings.NewReader(body))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		fmt.Printf("Error: %d - %s\n", resp.StatusCode, string(body))
		return
	}

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

PHP · cURL

<?php

$accountId = getenv('CLOUDFLARE_ACCOUNT_ID');
$scriptName = getenv('CLOUDFLARE_SCRIPT_NAME');
$authToken = getenv('CLOUDFLARE_API_TOKEN');

$url = "https://api.cloudflare.com/client/v4/accounts/{$accountId}/workers/scripts/{$scriptName}";
$headers = [
    'Authorization: Bearer ' . $authToken,
    'Content-Type: application/javascript'
];
$body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })';

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

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode >= 400) {
    echo "Error: {$httpCode} - {$response}\n";
} else {
    echo $response;
}

Ruby · net/http

require 'net/http'
require 'json'

account_id = ENV['CLOUDFLARE_ACCOUNT_ID']
script_name = ENV['CLOUDFLARE_SCRIPT_NAME']
auth_token = ENV['CLOUDFLARE_API_TOKEN']

uri = URI.parse("https://api.cloudflare.com/client/v4/accounts/#{account_id}/workers/scripts/#{script_name}")
req = Net::HTTP::Post.new(uri)
req['Authorization'] = "Bearer #{auth_token}"
req['Content-Type'] = 'application/javascript'
req.body = 'addEventListener("fetch", event => { event.respondWith(new Response("Hello")) })'

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

response = http.request(req)
if response.code.to_i >= 400
  puts "Error: #{response.code} - #{response.body}"
else
  puts response.body
end

Swift · URLSession

import Foundation

let accountId = ProcessInfo.processInfo.environment["CLOUDFLARE_ACCOUNT_ID"] ?? ""
let scriptName = ProcessInfo.processInfo.environment["CLOUDFLARE_SCRIPT_NAME"] ?? ""
let authToken = ProcessInfo.processInfo.environment["CLOUDFLARE_API_TOKEN"] ?? ""

let url = URL(string: "https://api.cloudflare.com/client/v4/accounts/" + accountId + "/workers/scripts/" + scriptName)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + authToken, forHTTPHeaderField: "Authorization")
request.setValue("application/javascript", forHTTPHeaderField: "Content-Type")
let body = "addEventListener(\"fetch\", event => { event.respondWith(new Response(\"Hello\")) })"
request.httpBody = body.data(using: .utf8)

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 >= 400 else {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
        return
    }
    if let data = data, let responseBody = String(data: data, encoding: .utf8) {
        print("Error: \(httpResponse.statusCode) - \(responseBody)")
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest::blocking::Client;
use reqwest::header;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let account_id = env::var("CLOUDFLARE_ACCOUNT_ID")?;
    let script_name = env::var("CLOUDFLARE_SCRIPT_NAME")?;
    let auth_token = env::var("CLOUDFLARE_API_TOKEN")?;

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

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

    let body = "addEventListener(\"fetch\", event => { event.respondWith(new Response(\"Hello\")) })";

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

    if !response.status().is_success() {
        eprintln!(
            "Error: {} - {}",
            response.status(),
            response.text()?
        );
    } else {
        println!("{}", response.text()?);
    }

    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var accountId = Environment.GetEnvironmentVariable("CLOUDFLARE_ACCOUNT_ID");
        var scriptName = Environment.GetEnvironmentVariable("CLOUDFLARE_SCRIPT_NAME");
        var authToken = Environment.GetEnvironmentVariable("CLOUDFLARE_API_TOKEN");

        var url = $"https://api.cloudflare.com/client/v4/accounts/{accountId}/workers/scripts/{scriptName}";
        var body = "addEventListener(\"fetch\", event => { event.respondWith(new Response(\"Hello\")) })";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);
        client.DefaultRequestHeaders.Add("Content-Type", "application/javascript");

        var response = await client.PostAsync(url, new StringContent(body));
        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

Translation notes

  • All implementations use environment variables for secrets (CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_SCRIPT_NAME, CLOUDFLARE_API_TOKEN)
  • Python implementations use both requests and httpx for completeness
  • Go implementation uses strings.NewReader for the body as io.NopCloser requires a reader
  • Swift uses URLSession with async/await pattern via RunLoop for simplicity in a CLI context
  • Rust uses reqwest blocking client for simplicity in a CLI context
  • C# uses async/await pattern with HttpClient

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Using raw strings for JSON bodies instead of proper serialization
  • Ignoring HTTP status codes and assuming success
  • Not setting the correct Content-Type header for raw JavaScript
  • In Go, forgetting to close the response body or handle errors properly
  • In Swift, not running the task in a run loop for CLI applications

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 are environment variables used instead of hardcoding secrets?

Environment variables are used to avoid hardcoding sensitive information like API tokens in the source code, which is a security best practice.

How do I set the environment variables for these examples?

For local development, you can set them in your shell: export CLOUDFLARE_ACCOUNT_ID=your_account_id, export CLOUDFLARE_SCRIPT_NAME=your_script_name, export CLOUDFLARE_API_TOKEN=your_api_token. For production, use a secrets manager or deployment environment variables.

Why does the Go implementation use strings.NewReader?

The Go http.NewRequest requires a io.Reader for the body. strings.NewReader provides a simple way to convert a string to a reader.

Can I use async/await in Go?

Yes, but the example uses the blocking client for simplicity in a CLI context. For production, consider using the async http.Client from the net/http package.