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/filename.txt -H "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example" -T filename.txt

Python · requests

import os
import requests

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

with open("filename.txt", "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/filename.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER"),
    "Host": "s3.amazonaws.com",
    "x-amz-date": os.environ.get("AWS_X_AMZ_DATE")
}

with httpx.stream("PUT", url, headers=headers, files={"file": open("filename.txt", "rb")}) as response:
    response.raise_for_status()

Node.js · fetch

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

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

fetch(url, {
  method: 'PUT',
  headers: headers,
  body: fs.createReadStream('filename.txt')
}).then(response => {
  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/filename.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER,
  'Host': 's3.amazonaws.com',
  'x-amz-date': process.env.AWS_X_AMZ_DATE
};

axios.put(url, fs.createReadStream('filename.txt'), { headers })
  .then(response => {
    if (response.status >= 400) throw new Error(`HTTP error! status: ${response.status}`);
  });

Go · net/http

package main

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

func main() {
	url := "https://s3.amazonaws.com/my-bucket/filename.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("Host", "s3.amazonaws.com")
	req.Header.Set("x-amz-date", os.Getenv("AWS_X_AMZ_DATE"))

	file, err := os.Open("filename.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 >= 400 {
		log.Fatalf("HTTP error! status: %d", resp.StatusCode)
	}
}

PHP · cURL

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

$context = stream_context_create([
    'http' => [
        'method' => 'PUT',
        'header' => $headers,
        'content' => file_get_contents('filename.txt')
    ]
]);

$response = file_get_contents($url, false, $context);
if ($http_response_header[0] === 'HTTP/1.1 200 OK') {
    // Success
} else {
    throw new Exception('HTTP error! status: ' . $http_response_header[0]);
}
?>

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/my-bucket/filename.txt')
req = Net::HTTP::Put.new(url.path)
req['Authorization'] = ENV['AWS_AUTH_HEADER']
req['Host'] = 's3.amazonaws.com'
req['x-amz-date'] = ENV['AWS_X_AMZ_DATE']

file = File.open('filename.txt', 'rb')
req.body_stream = file

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

unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{response.code}"
end

Swift · URLSession

import Foundation

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

let fileURL = URL(fileURLWithPath: "filename.txt")
let task = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in
    if let error = error {
        fatalError(error.localizedDescription)
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode < 400 else {
        fatalError("HTTP error! status: \(response?.description ?? "unknown")")
    }
}
task.resume()

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/filename.txt";
    let auth_header = env::var("AWS_AUTH_HEADER")?;
    let x_amz_date = env::var("AWS_X_AMZ_DATE")?;

    let mut file = File::open("filename.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("Host", "s3.amazonaws.com")
        .header("x-amz-date", x_amz_date)
        .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/filename.txt";
        var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER");
        var xAmzDate = Environment.GetEnvironmentVariable("AWS_X_AMZ_DATE");

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

        client.DefaultRequestHeaders.Add("Authorization", authHeader);
        client.DefaultRequestHeaders.Add("Host", "s3.amazonaws.com");
        client.DefaultRequestHeaders.Add("x-amz-date", xAmzDate);

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

Translation notes

  • AWS authentication headers are complex and typically generated dynamically; this example assumes they are precomputed and stored in environment variables.
  • The 'Host' header is explicitly set to match the cURL behavior, though some HTTP clients may set it automatically.
  • File uploads are handled via streaming where possible to avoid loading the entire file into memory.
  • Error handling is minimal but includes status code checks and basic exception handling.

Common pitfalls when porting

  • Forgetting to set the 'Host' header explicitly may cause issues with some HTTP clients that do not auto-populate it.
  • Not using streaming for large files can lead to high memory usage or crashes.
  • Assuming the AWS auth header is static; in practice, it should be regenerated for each request with the correct timestamp.
  • Ignoring SSL/TLS certificate validation in production environments can lead to security vulnerabilities.

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 'Host' header explicitly set?

Some HTTP clients (especially in Go and lower-level libraries) do not automatically set the 'Host' header to match the URL's host. Explicitly setting it ensures fidelity with the cURL command.

How do I generate the AWS auth header dynamically?

Use the AWS SDK for your language (e.g., boto3 for Python, AWS SDK for JavaScript) to generate the header with the correct signature for each request. The header includes a timestamp, so it must be regenerated for each request.

Can I use a raw string for the file body instead of streaming?

Yes, but it is not recommended for large files. Streaming is more memory-efficient and aligns with best practices for handling file uploads.