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/object-key \
  -H "x-amz-date: 20230101T120000Z" \
  -H "Authorization: AWS4-HMAC-SHA256 Credential=AKIA1234567890/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890" \
  -d 'binary-data' --upload-file

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/my-bucket/object-key"
headers = {
    "x-amz-date": "20230101T120000Z",
    "Authorization": f"AWS4-HMAC-SHA256 Credential={os.environ.get('AWS_ACCESS_KEY_ID')}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature={os.environ.get('AWS_SECRET_ACCESS_KEY')}"
}

with open('binary-data', 'rb') as f:
    response = requests.put(url, headers=headers, data=f)

response.raise_for_status()

Python · httpx

import os
import httpx

url = "https://s3.amazonaws.com/my-bucket/object-key"
headers = {
    "x-amz-date": "20230101T120000Z",
    "Authorization": f"AWS4-HMAC-SHA256 Credential={os.environ.get('AWS_ACCESS_KEY_ID')}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature={os.environ.get('AWS_SECRET_ACCESS_KEY')}"
}

with httpx.stream("PUT", url, headers=headers) as response:
    with open('binary-data', 'rb') as f:
        for chunk in f:
            response.stream.send(chunk)
    response.raise_for_status()

Node.js · fetch

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

const url = 'https://s3.amazonaws.com/my-bucket/object-key';
const headers = {
  'x-amz-date': '20230101T120000Z',
  'Authorization': `AWS4-HMAC-SHA256 Credential=${process.env.AWS_ACCESS_KEY_ID}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=${process.env.AWS_SECRET_ACCESS_KEY}`
};

(async () => {
  const fileStream = fs.createReadStream('binary-data');
  const response = await fetch(url, { method: 'PUT', headers, body: fileStream });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
})();

Node.js · axios

const fs = require('fs');
const axios = require('axios');

const url = 'https://s3.amazonaws.com/my-bucket/object-key';
const headers = {
  'x-amz-date': '20230101T120000Z',
  'Authorization': `AWS4-HMAC-SHA256 Credential=${process.env.AWS_ACCESS_KEY_ID}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=${process.env.AWS_SECRET_ACCESS_KEY}`
};

(async () => {
  const response = await axios.put(url, fs.createReadStream('binary-data'), { headers });
  if (response.status >= 400) throw new Error(`HTTP error! status: ${response.status}`);
})();

Go · net/http

package main

import (
	"bytes"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	url := "https://s3.amazonaws.com/my-bucket/object-key"
	req, err := http.NewRequest("PUT", url, nil)
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("x-amz-date", "20230101T120000Z")
	req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential="+os.Getenv("AWS_ACCESS_KEY_ID")+"/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature="+os.Getenv("AWS_SECRET_ACCESS_KEY"))

	file, err := os.Open("binary-data")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	req.Body = file
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		log.Fatalf("HTTP error! status: %s", resp.Status)
	}
}

PHP · cURL

<?php
$url = 'https://s3.amazonaws.com/my-bucket/object-key';
$headers = [
    'x-amz-date: 20230101T120000Z',
    'Authorization: AWS4-HMAC-SHA256 Credential=' . getenv('AWS_ACCESS_KEY_ID') . '/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=' . getenv('AWS_SECRET_ACCESS_KEY')
];

$file = fopen('binary-data', 'r');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_INFILE, $file);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('binary-data'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) >= 400) {
    throw new Exception('HTTP error! status: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE));
}
curl_close($ch);
fclose($file);

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/my-bucket/object-key')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Put.new(url.path)
request['x-amz-date'] = '20230101T120000Z'
request['Authorization'] = "AWS4-HMAC-SHA256 Credential=#{ENV['AWS_ACCESS_KEY_ID']}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=#{ENV['AWS_SECRET_ACCESS_KEY']}"

file = File.open('binary-data', 'rb')
request.body_stream = file

response = http.request(request)
if response.code.to_i >= 400
  raise "HTTP error! status: #{response.code}"
end
file.close

Swift · URLSession

import Foundation

let url = URL(string: "https://s3.amazonaws.com/my-bucket/object-key")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("20230101T120000Z", forHTTPHeaderField: "x-amz-date")
request.setValue("AWS4-HMAC-SHA256 Credential=#{ProcessInfo.processInfo.environment["AWS_ACCESS_KEY_ID"]}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=#{ProcessInfo.processInfo.environment["AWS_SECRET_ACCESS_KEY"]}", forHTTPHeaderField: "Authorization")

let fileURL = URL(fileURLWithPath: "binary-data")
let fileData = try Data(contentsOf: fileURL)

let task = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode < 400 else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use std::fs::File;
use std::io::Read;
use reqwest::blocking::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://s3.amazonaws.com/my-bucket/object-key";
    let client = Client::new();
    let mut file = File::open("binary-data")?;
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer)?;

    let response = client
        .put(url)
        .header("x-amz-date", "20230101T120000Z")
        .header("Authorization", format!("AWS4-HMAC-SHA256 Credential={}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature={}", env::var("AWS_ACCESS_KEY_ID")?, env::var("AWS_SECRET_ACCESS_KEY")?))
        .body(buffer)
        .send()?;

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

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var url = "https://s3.amazonaws.com/my-bucket/object-key";
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Put, url);
        request.Headers.Add("x-amz-date", "20230101T120000Z");
        request.Headers.Add("Authorization", $"AWS4-HMAC-SHA256 Credential={Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID")}/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature={Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY")}");

        var fileBytes = await File.ReadAllBytesAsync("binary-data");
        request.Content = new ByteArrayContent(fileBytes);

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

Translation notes

  • All implementations use environment variables for AWS credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
  • The cURL command uses `--upload-file` which is translated to streaming the file content in most clients.
  • Go and Rust use blocking clients for simplicity; async variants would be more idiomatic in production.
  • PHP uses curl with file streaming for PUT requests.
  • Swift uses URLSession with uploadTask for file uploads.
  • Error handling is minimal but checks HTTP status codes.

Common pitfalls when porting

  • Forgetting to set AWS credentials in environment variables will cause authentication failures.
  • Using raw strings for AWS signatures in code (instead of env vars) is a security risk.
  • Not closing file handles or streams can lead to resource leaks.
  • In Go, using http.NewRequest with a nil body and then setting Body later can cause issues if not handled carefully.
  • In Python, using requests.put with a file stream requires proper context management to avoid file handle leaks.

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 AWS credentials read from environment variables instead of being hardcoded?

Hardcoding credentials in code is a security risk. Environment variables allow credentials to be injected at runtime without exposing them in version control or logs.

Can I use async/await in Go or Rust for better performance?

Yes, but the examples use blocking clients for simplicity. In production, consider using async variants like reqwest::Client in Rust or net/http with goroutines in Go.

Why does the Swift example use RunLoop.main.run()?

It's a simple way to keep the program running to await the async task completion in a synchronous context. In a real app, you'd typically use async/await with Swift 5.5+.