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/bucket-name/object-key -H "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890abcdef" -T /path/to/local/file

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/bucket-name/object-key"
headers = {
    "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')}",
    "x-amz-date": "20230101T000000Z"
}

with open("/path/to/local/file", "rb") as file:
    response = requests.put(url, headers=headers, data=file)
    response.raise_for_status()
    print(response.text)

Python · httpx

import os
import httpx

url = "https://s3.amazonaws.com/bucket-name/object-key"
headers = {
    "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')}",
    "x-amz-date": "20230101T000000Z"
}

with httpx.stream("PUT", url, headers=headers, content=open("/path/to/local/file", "rb")) as response:
    response.raise_for_status()
    print(response.text)

Node.js · fetch

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

const url = 'https://s3.amazonaws.com/bucket-name/object-key';
const headers = {
  '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}`,
  'x-amz-date': '20230101T000000Z'
};

fetch(url, {
  method: 'PUT',
  headers: headers,
  body: fs.createReadStream('/path/to/local/file')
})
  .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 fs = require('fs');
const axios = require('axios');

const url = 'https://s3.amazonaws.com/bucket-name/object-key';
const headers = {
  '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}`,
  'x-amz-date': '20230101T000000Z'
};

axios.put(url, fs.createReadStream('/path/to/local/file'), { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

Go · net/http

package main

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

func main() {
	url := "https://s3.amazonaws.com/bucket-name/object-key"
	authHeader := fmt.Sprintf("AWS4-HMAC-SHA256 Credential=%s/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=%s",
		os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"))

	file, err := os.Open("/path/to/local/file")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	body, err := ioutil.ReadAll(file)
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(body))
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", authHeader)
	req.Header.Set("x-amz-date", "20230101T000000Z")

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

	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("HTTP error! status: %s", resp.Status))
	}

	bodyResp, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(bodyResp))
}

PHP · cURL

<?php
$url = 'https://s3.amazonaws.com/bucket-name/object-key';
$headers = [
    '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'),
    'x-amz-date: 20230101T000000Z'
];

$file = fopen('/path/to/local/file', 'r');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $file);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('/path/to/local/file'));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
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);
if ($httpCode !== 200) {
    die("HTTP error! status: $httpCode");
}

fclose($file);
curl_close($ch);

echo $response;
?>

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/bucket-name/object-key')
headers = {
  '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']}",
  'x-amz-date' => '20230101T000000Z'
}

file = File.open('/path/to/local/file', 'rb')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Put.new(url.request_uri, headers)
request.body_stream = file

response = http.request(request)
file.close

if response.code != '200'
  raise "HTTP error! status: #{response.code}"
end

puts response.body

Swift · URLSession

import Foundation

let url = URL(string: "https://s3.amazonaws.com/bucket-name/object-key")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("AWS4-HMAC-SHA256 Credential=ACCESS_KEY/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=SECRET_KEY", forHTTPHeaderField: "Authorization")
request.setValue("20230101T000000Z", forHTTPHeaderField: "x-amz-date")

let fileURL = URL(fileURLWithPath: "/path/to/local/file")
let fileData = try Data(contentsOf: fileURL)

let task = URLSession.shared.uploadTask(with: request, from: fileData) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print(responseString)
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://s3.amazonaws.com/bucket-name/object-key";
    let auth_header = 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")?
    );

    let mut file = File::open("/path/to/local/file")?;
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer)?;

    let client = reqwest::Client::new();
    let response = client.put(url)
        .header("Authorization", auth_header)
        .header("x-amz-date", "20230101T000000Z")
        .body(buffer)
        .send()
        .await?;

    if !response.status().is_success() {
        panic!("HTTP error! status: {}", response.status());
    }

    let body = response.text().await?;
    println!("{}", body);
    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/bucket-name/object-key";
        var authHeader = $"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")}";

        using var client = new HttpClient();
        using var fileStream = File.OpenRead("/path/to/local/file");
        using var content = new StreamContent(fileStream);

        client.DefaultRequestHeaders.Add("Authorization", authHeader);
        client.DefaultRequestHeaders.Add("x-amz-date", "20230101T000000Z");

        var response = await client.PutAsync(url, content);
        response.EnsureSuccessStatusCode();

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

Translation notes

  • AWS signature generation is simplified; in production, use AWS SDKs for proper signing
  • File path is hardcoded; consider making it configurable
  • Error handling is minimal but includes status check and body read
  • Environment variables are used for credentials as per best practices

Common pitfalls when porting

  • Forgetting to set 'x-amz-date' header can cause authentication failures
  • Not closing file handles in Go/Ruby/Python can lead to resource leaks
  • In Swift, the example uses synchronous code for simplicity; production code should use async/await
  • In Rust, the example requires the 'reqwest' and 'tokio' crates
  • In C#, the example uses synchronous file operations; consider async alternatives for large files

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 signature not generated dynamically?

The cURL command provided a pre-signed signature. In production, use AWS SDKs (e.g., boto3 for Python) to generate signatures dynamically for better security and maintainability.

Can I use a different file path dynamically?

Yes, pass the file path as a command-line argument, environment variable, or configuration parameter instead of hardcoding it.

Why is the 'x-amz-date' header hardcoded?

The cURL command did not include a dynamic date. In production, generate the current timestamp dynamically for each request.