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

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/my-bucket/path/to/file.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_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/path/to/file.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER")
}

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

Node.js · fetch

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

const url = 'https://s3.amazonaws.com/my-bucket/path/to/file.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER
};

const response = await fetch(url, {
  method: 'PUT',
  headers,
  body: fs.createReadStream('local_file.txt')
});

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

Node.js · axios

import axios from 'axios';
import fs from 'fs';
import FormData from 'form-data';

const url = 'https://s3.amazonaws.com/my-bucket/path/to/file.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER
};

const form = new FormData();
form.append('file', fs.createReadStream('local_file.txt'));

const response = await axios.put(url, form, {
  headers: { ...headers, ...form.getHeaders() }
});

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/path/to/file.txt"
	authHeader := os.Getenv("AWS_AUTH_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)

	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/path/to/file.txt';
$headers = [
    'Authorization: ' . getenv('AWS_AUTH_HEADER')
];

$file = fopen('local_file.txt', '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('local_file.txt'));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($httpCode >= 400) {
    throw new Exception("HTTP error! status: $httpCode");
}

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/my-bucket/path/to/file.txt')
auth_header = ENV['AWS_AUTH_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.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/path/to/file.txt")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue(ProcessInfo.processInfo.environment["AWS_AUTH_HEADER"], forHTTPHeaderField: "Authorization")

let fileURL = URL(fileURLWithPath: "local_file.txt")
let (data, response) = try FileManager.default.contents(atPath: fileURL.path)!

let (_, responseData) = try URLSession.shared.uploadTask(with: request, from: data).wait()

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

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/path/to/file.txt";
    let auth_header = env::var("AWS_AUTH_HEADER")?;

    let mut file = File::open("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)
        .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/path/to/file.txt";
        var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER");

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

        client.DefaultRequestHeaders.Add("Authorization", authHeader);
        var response = await client.PutAsync(url, content);

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }
    }
}

Translation notes

  • All implementations read the AWS authorization header from an environment variable named AWS_AUTH_HEADER.
  • The Go, Rust, and C# examples use blocking I/O for simplicity. Async variants are available in those languages.
  • The Swift example uses URLSession's uploadTask for simplicity, but could also use URLSession.dataTask with a file URL.
  • PHP uses cURL's PUT method with a file handle for streaming upload.
  • Python's httpx example uses streaming for large files.
  • Node.js examples use form-data for multipart uploads, which is compatible with S3's requirements.

Common pitfalls when porting

  • Forgetting to set the AWS_AUTH_HEADER environment variable will cause authentication failures.
  • Not handling file streams properly may lead to memory issues with large files.
  • In Go, forgetting to close the file or response body can lead to resource leaks.
  • In Swift, the example assumes the file exists at the given path; proper error handling for file access is omitted for brevity.
  • In Rust, the blocking client is used; for async, use reqwest::Client with async/await.
  • In C#, the HttpClient should be reused for performance; creating a new instance per request is not recommended.

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 authorization header stored in an environment variable?

Storing sensitive credentials in environment variables is a security best practice. It avoids hardcoding secrets in source code and allows for easy rotation without modifying the code.

Can I use a different HTTP library in these languages?

Yes, most languages have multiple HTTP libraries. The examples use idiomatic libraries for each language, but alternatives like urllib in Python or RestSharp in C# could also be used.

How do I handle large file uploads efficiently?

Use streaming or chunked uploads where possible. Libraries like httpx in Python, URLSession in Swift, and HttpClient in C# support streaming uploads to avoid loading the entire file into memory.

Why does the Node.js example use form-data?

S3's PUT operation with a file can be handled as a raw upload or multipart. The form-data library simplifies multipart uploads and is commonly used in Node.js for such operations.