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=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example" \
  -T "localfile.txt"

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/my-bucket/file.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER", "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example")
}

with open("localfile.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", "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example")
}

with httpx.stream("PUT", url, headers=headers, files={"file": open("localfile.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/file.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER || 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example'
};

const fileStream = fs.createReadStream('localfile.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

import axios from 'axios';
import fs from 'fs';

const url = 'https://s3.amazonaws.com/my-bucket/file.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER || 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example'
};

const response = await axios.put(url, fs.createReadStream('localfile.txt'), { headers });

if (response.status !== 200) {
  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/file.txt"
	authHeader := os.Getenv("AWS_AUTH_HEADER")
	if authHeader == "" {
		authHeader = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example"
	}

	file, err := os.Open("localfile.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)

	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("HTTP error! status: %d", resp.StatusCode)
	}
}

PHP · cURL

<?php
$url = 'https://s3.amazonaws.com/my-bucket/file.txt';
$authHeader = getenv('AWS_AUTH_HEADER') ?: 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example';

$file = fopen('localfile.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('localfile.txt'));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: ' . $authHeader]);
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) {
    die("HTTP error! status: $httpCode");
}

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/my-bucket/file.txt')
auth_header = ENV.fetch('AWS_AUTH_HEADER', 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example')

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

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

request = Net::HTTP::Put.new(url.request_uri)
request['Authorization'] = auth_header
request.body_stream = file

response = http.request(request)
file.close

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/file.txt")!
let authHeader = ProcessInfo.processInfo.environment["AWS_AUTH_HEADER"] ?? "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example"

let fileURL = URL(fileURLWithPath: "localfile.txt")
let fileData = try Data(contentsOf: fileURL)

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue(authHeader, forHTTPHeaderField: "Authorization")
request.httpBody = fileData

let (data, response) = try await URLSession.shared.data(for: request)

if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
    fatalError("HTTP error! status: \(httpResponse.statusCode)")
}

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/my-bucket/file.txt";
    let auth_header = env::var("AWS_AUTH_HEADER").unwrap_or_else(|_| "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example".to_string());

    let mut file = File::open("localfile.txt")?;
    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)
        .body(buffer)
        .send()
        .await?;

    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/file.txt";
        var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER") ?? "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20231001/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=example";

        using var fileStream = File.OpenRead("localfile.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);

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

Translation notes

  • All implementations read the Authorization header from an environment variable named AWS_AUTH_HEADER for security.
  • The PUT method and raw file upload are preserved in all translations.
  • Error handling checks for non-2xx status codes and raises/throws an exception.
  • File streams are used where possible to avoid loading entire files into memory.
  • Python httpx uses streaming for file uploads to match the cURL behavior.

Common pitfalls when porting

  • Forgetting to set the Authorization header from the environment variable.
  • Not properly handling file streams (e.g., closing files or streams).
  • Assuming the file exists without checking (e.g., in Go or Rust).
  • Ignoring SSL/TLS verification in Go or Swift (not shown here but important in production).
  • Using synchronous file reads in async contexts (e.g., Swift or Rust).

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 Authorization header redacted in the parsed output?

The Authorization header contains a signature that should be treated as a secret. It is replaced with an environment variable reference in the code to avoid hardcoding sensitive values.

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

Yes, but the examples use the most idiomatic and widely-used libraries for each language to ensure clarity and maintainability.

How do I handle large files efficiently?

All examples use streaming or file streams to avoid loading the entire file into memory, which is critical for large files.