Qaynaq LABS · TOOLS

CURL → CODE · PUT · API-KEY

cURL → 10 languages

PUT s3.amazonaws.com · body: raw · secrets replaced with env vars.

Source cURL
curl -X PUT https://s3.amazonaws.com/my-bucket/data/file.txt \
  -H "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Content-Type: text/plain" \
  -d "Updated content"

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/my-bucket/data/file.txt"
auth_header = os.environ.get("AWS_AUTH_HEADER")
headers = {
    "Authorization": auth_header,
    "Content-Type": "text/plain"
}
body = "Updated content"

response = requests.put(url, headers=headers, data=body)
if response.status_code >= 400:
    print(response.text)
else:
    print("Success")

Python · httpx

import os
import httpx

url = "https://s3.amazonaws.com/my-bucket/data/file.txt"
auth_header = os.environ.get("AWS_AUTH_HEADER")
headers = {
    "Authorization": auth_header,
    "Content-Type": "text/plain"
}
body = "Updated content"

with httpx.Client() as client:
    response = client.put(url, headers=headers, content=body)
    if response.status_code >= 400:
        print(response.text)
    else:
        print("Success")

Node.js · fetch

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

const url = 'https://s3.amazonaws.com/my-bucket/data/file.txt';
const authHeader = process.env.AWS_AUTH_HEADER;
const headers = {
  'Authorization': authHeader,
  'Content-Type': 'text/plain'
};
const body = 'Updated content';

fetch(url, {
  method: 'PUT',
  headers: headers,
  body: body
})
  .then(response => {
    if (!response.ok) {
      return response.text().then(text => { throw new Error(text); });
    }
    return response.text();
  })
  .then(() => console.log('Success'))
  .catch(err => console.error(err.message));

Node.js · axios

const axios = require('axios');

const url = 'https://s3.amazonaws.com/my-bucket/data/file.txt';
const authHeader = process.env.AWS_AUTH_HEADER;
const headers = {
  'Authorization': authHeader,
  'Content-Type': 'text/plain'
};
const body = 'Updated content';

axios.put(url, body, { headers })
  .then(response => {
    console.log('Success');
  })
  .catch(error => {
    if (error.response) {
      console.error(error.response.data);
    } else {
      console.error(error.message);
    }
  });

Go · net/http

package main

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

func main() {
	url := "https://s3.amazonaws.com/my-bucket/data/file.txt"
	authHeader := os.Getenv("AWS_AUTH_HEADER")
	body := "Updated content"

	req, err := http.NewRequest("PUT", url, io.NopCloser(strings.NewReader(body)))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Authorization", authHeader)
	req.Header.Set("Content-Type", "text/plain")

	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.Println(string(body))
	} else {
		fmt.Println("Success")
	}
}

PHP · cURL

<?php

$url = 'https://s3.amazonaws.com/my-bucket/data/file.txt';
$authHeader = getenv('AWS_AUTH_HEADER');
$headers = [
    'Authorization: ' . $authHeader,
    'Content-Type: text/plain'
];
$body = 'Updated content';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($httpCode >= 400) {
    echo $response;
} else {
    echo "Success";
}

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/my-bucket/data/file.txt')
auth_header = ENV['AWS_AUTH_HEADER']
headers = {
  'Authorization' => auth_header,
  'Content-Type' => 'text/plain'
}
body = 'Updated content'

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

request = Net::HTTP::Put.new(url.request_uri, headers)
request.body = body

response = http.request(request)

if response.code.to_i >= 400
  puts response.body
else
  puts 'Success'
end

Swift · URLSession

import Foundation

let url = URL(string: "https://s3.amazonaws.com/my-bucket/data/file.txt")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue(ProcessInfo.processInfo.environment["AWS_AUTH_HEADER"], forHTTPHeaderField: "Authorization")
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.httpBody = "Updated content".data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print(error.localizedDescription)
        return
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    if httpResponse.statusCode >= 400 {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    } else {
        print("Success")
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://s3.amazonaws.com/my-bucket/data/file.txt";
    let auth_header = env::var("AWS_AUTH_HEADER")?;
    let body = "Updated content";

    let client = reqwest::Client::new();
    let response = client
        .put(url)
        .header("Authorization", auth_header)
        .header("Content-Type", "text/plain")
        .body(body)
        .send()
        .await?;

    if !response.status().is_success() {
        let body = response.text().await?;
        println!("{}", body);
    } else {
        println!("Success");
    }

    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var url = "https://s3.amazonaws.com/my-bucket/data/file.txt";
        var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER");
        var body = "Updated content";

        using var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Put, url);
        request.Headers.Add("Authorization", authHeader);
        request.Headers.Add("Content-Type", "text/plain");
        request.Content = new StringContent(body);

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        else
        {
            Console.WriteLine("Success");
        }
    }
}

Translation notes

  • All implementations read the AWS authorization header from an environment variable named AWS_AUTH_HEADER.
  • The raw body is sent as a string in all implementations.
  • Error handling checks the HTTP status code and prints the response body if the request fails.
  • Python implementations use requests and httpx, Node.js uses fetch and axios, Go uses net/http, PHP uses cURL, Ruby uses Net::HTTP, Swift uses URLSession, Rust uses reqwest, and C# uses HttpClient.
  • The Content-Type header is explicitly set to 'text/plain' as in the original cURL command.

Common pitfalls when porting

  • Forgetting to set the AWS_AUTH_HEADER environment variable will cause authentication failures.
  • In Go, ensure the body is properly closed to avoid resource leaks.
  • In Swift, the task must be started with task.resume() and the run loop must be kept alive for async operations.
  • In Rust, the reqwest client requires the tokio runtime for async operations.
  • In PHP, ensure the cURL handle is properly closed after use to avoid resource leaks.
  • In Python, using httpx requires installing the httpx library (pip install httpx).

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 is the AWS authorization header stored in an environment variable?

Storing sensitive credentials like API keys or authorization tokens in environment variables is a security best practice. It prevents accidental exposure in code repositories and allows for easier management of secrets across different environments.

Can I use a different HTTP client library in these languages?

Yes, you can use alternative HTTP client libraries in each language, but the provided implementations use the most idiomatic and widely-used libraries for simplicity and consistency.

How do I set the AWS_AUTH_HEADER environment variable?

The method depends on your operating system and shell. For example, in bash you can run `export AWS_AUTH_HEADER="your_value"` before running the script. In Windows Command Prompt, use `set AWS_AUTH_HEADER=your_value`.

Why is the body sent as a raw string instead of a JSON object?

The original cURL command sends a raw text body with Content-Type set to 'text/plain'. If the body were JSON, the Content-Type would typically be 'application/json', and the body would be a JSON string or object.