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/my-file.txt \
  --header "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230810/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=example" \
  --upload-file /path/to/local/file.txt

Python · requests

import os
import requests

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

with open("/path/to/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/my-file.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER"),
    "x-amz-content-sha256": os.environ.get("AWS_CONTENT_SHA256"),
    "x-amz-date": os.environ.get("AWS_DATE")
}

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

Node.js · fetch

import fs from 'fs';
import fetch from 'node-fetch';

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

const fileStream = fs.createReadStream('/path/to/local/file.txt');
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/my-file.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER,
  'x-amz-content-sha256': process.env.AWS_CONTENT_SHA256,
  'x-amz-date': process.env.AWS_DATE
};

const response = await axios.put(url, fs.createReadStream('/path/to/local/file.txt'), { headers });

if (response.status < 200 || response.status >= 300) {
  throw new Error(`Request failed with status ${response.status}`);
}

Go · net/http

package main

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

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

	req.Header.Set("Authorization", os.Getenv("AWS_AUTH_HEADER"))
	req.Header.Set("x-amz-content-sha256", os.Getenv("AWS_CONTENT_SHA256"))
	req.Header.Set("x-amz-date", os.Getenv("AWS_DATE"))

	file, err := os.Open("/path/to/local/file.txt")
	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 < 200 || resp.StatusCode >= 300 {
		log.Fatalf("Request failed with status %d", resp.StatusCode)
	}
}

PHP · cURL

<?php

$url = 'https://s3.amazonaws.com/my-bucket/my-file.txt';
$headers = [
    'Authorization: ' . getenv('AWS_AUTH_HEADER'),
    'x-amz-content-sha256: ' . getenv('AWS_CONTENT_SHA256'),
    'x-amz-date: ' . getenv('AWS_DATE')
];

$file = fopen('/path/to/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_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_INFILE, $file);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('/path/to/local/file.txt'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($httpCode < 200 || $httpCode >= 300) {
    die("Request failed with status $httpCode");
}

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/my-bucket/my-file.txt')
headers = {
  'Authorization' => ENV['AWS_AUTH_HEADER'],
  'x-amz-content-sha256' => ENV['AWS_CONTENT_SHA256'],
  'x-amz-date' => ENV['AWS_DATE']
}

file = File.open('/path/to/local/file.txt', '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

unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed with status #{response.code}"
end

Swift · URLSession

import Foundation

let url = URL(string: "https://s3.amazonaws.com/my-bucket/my-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_CONTENT_SHA256"], forHTTPHeaderField: "x-amz-content-sha256")
request.setValue(ProcessInfo.processInfo.environment["AWS_DATE"], forHTTPHeaderField: "x-amz-date")

let fileURL = URL(fileURLWithPath: "/path/to/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 {
        fatalError("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        fatalError("Request failed with status \(httpResponse.statusCode)")
    }
}
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/my-file.txt";
    let auth_header = env::var("AWS_AUTH_HEADER")?;
    let content_sha = env::var("AWS_CONTENT_SHA256")?;
    let date = env::var("AWS_DATE")?;

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

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

    if !response.status().is_success() {
        return Err(format!("Request failed with 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/my-file.txt";
        var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER");
        var contentSha = Environment.GetEnvironmentVariable("AWS_CONTENT_SHA256");
        var date = Environment.GetEnvironmentVariable("AWS_DATE");

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

        client.DefaultRequestHeaders.Add("Authorization", authHeader);
        client.DefaultRequestHeaders.Add("x-amz-content-sha256", contentSha);
        client.DefaultRequestHeaders.Add("x-amz-date", date);

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

Translation notes

  • All implementations use environment variables for sensitive headers.
  • File uploads are handled via streaming where possible to avoid memory issues.
  • Error handling checks HTTP status codes but does not parse response bodies.
  • Go and Rust use blocking clients for simplicity; async variants are available.
  • PHP uses cURL for direct file upload support.

Common pitfalls when porting

  • Forgetting to set Content-Length or equivalent headers can cause issues with some servers.
  • Not closing file handles or streams can lead to resource leaks.
  • Using raw strings for headers instead of environment variables risks secret exposure.
  • Assuming the server always returns JSON; always check status codes first.

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

The cURL command provided uses a pre-signed AWS signature. In production, you would typically use an AWS SDK to generate these headers dynamically rather than hardcoding them.

Can I use async/await in Python or Go?

Yes. In Python, use httpx.AsyncClient or aiohttp. In Go, use the http package with goroutines or a library like 'github.com/valyala/fasthttp' for high performance.

How do I handle large file uploads without loading the entire file into memory?

Use streaming uploads (supported in all provided examples) or chunked transfer encoding where the library supports it.