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/file.txt \
  -H "Authorization: AWS4-HMAC-SHA256 Credential=AKIA1234567890/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890abcdef" \
  -H "x-amz-date: 20230101T000000Z" \
  --upload-file local_file.txt

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/my-bucket/file.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER"),
    "x-amz-date": os.environ.get("AWS_DATE_HEADER")
}

with open("local_file.txt", "rb") as file:
    response = requests.put(url, headers=headers, data=file)
    response.raise_for_status()

Python · httpx

import os
import httpx

url = "https://s3.amazonaws.com/my-bucket/file.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER"),
    "x-amz-date": os.environ.get("AWS_DATE_HEADER")
}

with open("local_file.txt", "rb") as file:
    with httpx.Client() as client:
        response = client.put(url, headers=headers, content=file.read())
        response.raise_for_status()

Node.js · fetch

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

const url = 'https://s3.amazonaws.com/my-bucket/file.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER,
  'x-amz-date': process.env.AWS_DATE_HEADER
};

const fileStream = fs.createReadStream('local_file.txt');

fetch(url, {
  method: 'PUT',
  headers: headers,
  body: fileStream
})
.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/my-bucket/file.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER,
  'x-amz-date': process.env.AWS_DATE_HEADER
};

const fileStream = fs.createReadStream('local_file.txt');

axios.put(url, fileStream, { headers: headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Go · net/http

package main

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

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

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

	req, err := http.NewRequest("PUT", url, file)
	if err != nil {
		log.Fatal(err)
	}

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

	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("Request failed with status: %s", resp.Status)
	}
}

PHP · cURL

<?php
$url = 'https://s3.amazonaws.com/my-bucket/file.txt';
$headers = [
    'Authorization: ' . getenv('AWS_AUTH_HEADER'),
    'x-amz-date: ' . getenv('AWS_DATE_HEADER')
];

$file = fopen('local_file.txt', 'r');
if (!$file) {
    die('Unable to open file.');
}

$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('local_file.txt'));
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("Request failed with status: $httpCode");
}

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

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/my-bucket/file.txt')
auth_header = ENV['AWS_AUTH_HEADER']
x_amz_date = ENV['AWS_DATE_HEADER']

file = File.open('local_file.txt', 'rb')

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

request = Net::HTTP::Put.new(url.path)
request['Authorization'] = auth_header
request['x-amz-date'] = x_amz_date
request.body_stream = file

response = http.request(request)
if response.code != '200'
  raise "Request failed with status: #{response.code}"
end

file.close

Swift · URLSession

import Foundation

let url = URL(string: "https://s3.amazonaws.com/my-bucket/file.txt")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue(ProcessInfo.processInfo.environment["AWS_AUTH_HEADER"], forHTTPHeaderField: "Authorization")
request.setValue(ProcessInfo.processInfo.environment["AWS_DATE_HEADER"], forHTTPHeaderField: "x-amz-date")

let fileURL = URL(fileURLWithPath: "local_file.txt")
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("Request failed with status: \(response?.description ?? "unknown")")
        return
    }
    print("Success")
}

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<(), reqwest::Error> {
    let url = "https://s3.amazonaws.com/my-bucket/file.txt";
    let auth_header = env::var("AWS_AUTH_HEADER").expect("AWS_AUTH_HEADER not set");
    let x_amz_date = env::var("AWS_DATE_HEADER").expect("AWS_DATE_HEADER not set");

    let mut file = File::open("local_file.txt").expect("Unable to open file");
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer).expect("Unable to read file");

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

    if !response.status().is_success() {
        panic!("Request failed with status: {}", response.status());
    }

    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/file.txt";
        var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER");
        var xAmzDate = Environment.GetEnvironmentVariable("AWS_DATE_HEADER");

        using var fileStream = File.OpenRead("local_file.txt");
        using var client = new HttpClient();
        using var content = new StreamContent(fileStream);

        var request = new HttpRequestMessage(HttpMethod.Put, url)
        {
            Content = content
        };
        request.Headers.Add("Authorization", authHeader);
        request.Headers.Add("x-amz-date", xAmzDate);

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

Translation notes

  • All implementations read AWS auth headers from environment variables for security.
  • File uploads are handled as streams or raw bytes to avoid memory issues with large files.
  • Error handling is minimal but includes status code checks and basic error logging.
  • The Go implementation uses a file stream directly in the request body.
  • The Swift implementation uses URLSession's uploadTask for simplicity.
  • The Rust implementation uses async/await with reqwest for async I/O.
  • The C# implementation uses HttpClient with StreamContent for efficient file uploads.

Common pitfalls when porting

  • Forgetting to set environment variables for AWS auth headers will cause failures.
  • Not closing file handles or streams can lead to resource leaks.
  • Assuming the file exists without checking can cause runtime errors.
  • Ignoring SSL/TLS verification (not shown here) can be a security risk in production.
  • In Go, not deferring file closure can lead to file handle leaks.
  • In Python, using requests with large files may consume significant memory if not streamed properly.

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 the AWS auth headers read from environment variables?

Storing secrets in environment variables is a security best practice to avoid hardcoding sensitive data in source code or version control.

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

Yes, but the examples use idiomatic libraries for each language to maintain consistency and readability. Alternative libraries may require different syntax.

How do I handle large file uploads efficiently?

Most libraries support streaming or chunked uploads. For example, in Python, use `requests` with a file stream or `httpx` with `content=file.read()` in chunks.

What if I need to add query parameters to the URL?

Append them to the URL string, e.g., `https://s3.amazonaws.com/my-bucket/file.txt?param=value`. Libraries like `requests` or `axios` also support a `params` option for query strings.