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

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/my-bucket/path/to/object.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER", "")
}

with open("local.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/object.txt"
headers = {
    "Authorization": os.environ.get("AWS_AUTH_HEADER", "")
}

with httpx.stream("PUT", url, headers=headers, content=open("local.txt", "rb")) as response:
    response.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/path/to/object.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER
};

(async () => {
  const fileStream = fs.createReadStream('local.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/path/to/object.txt';
const headers = {
  'Authorization': process.env.AWS_AUTH_HEADER
};

(async () => {
  const response = await axios.put(url, fs.createReadStream('local.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/path/to/object.txt"
	req, err := http.NewRequest("PUT", url, nil)
	if err != nil {
		log.Fatal(err)
	}

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

	req.Header.Set("Authorization", os.Getenv("AWS_AUTH_HEADER"))
	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/path/to/object.txt';
$headers = ['Authorization: ' . getenv('AWS_AUTH_HEADER')];

$file = fopen('local.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.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 || $httpCode >= 300) {
    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/path/to/object.txt')
req = Net::HTTP::Put.new(url)
req['Authorization'] = ENV['AWS_AUTH_HEADER']

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

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

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

Swift · URLSession

import Foundation

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

let fileURL = URL(fileURLWithPath: "local.txt")
let (data, response) = try FileManager.default.contentsOfFile(fileURL.path)

let task = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("Request failed with status \(response?.httpStatusCode ?? 0)")
    }
}
task.resume()
task.waitUntilFinished()

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

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

        using var client = new HttpClient();
        using var fileStream = File.OpenRead("local.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($"Request failed with status {response.StatusCode}");
        }
    }
}

Translation notes

  • AWS4-HMAC-SHA256 auth is treated as an API key for simplicity; actual signing requires more complex logic.
  • File uploads are streamed where possible to avoid loading entire files into memory.
  • Error handling is minimal but includes status code checks and basic exceptions.
  • Environment variables are used for sensitive headers (e.g., AWS_AUTH_HEADER).

Common pitfalls when porting

  • For AWS S3, the Authorization header must be signed with AWS credentials; hardcoding or incorrect signing will fail.
  • In Go, ensure the file handle is properly closed to avoid resource leaks.
  • In Swift, the example uses synchronous wait for simplicity; in production, use async/await or completion handlers.
  • In Rust, the reqwest client requires the tokio runtime for async operations.
  • In PHP, ensure the file handle is closed after the request to avoid resource leaks.

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 treated as an API key instead of being signed?

AWS4-HMAC-SHA256 signing is complex and requires additional logic (e.g., AWS SDKs handle this). For simplicity, the header is treated as a raw API key. Use AWS SDKs for production.

How do I handle large file uploads efficiently?

Stream the file content (e.g., using file handles or streams) rather than loading the entire file into memory. Most libraries support streaming.

Why is the Go example using a file handle directly?

The Go http.Request.Body expects an io.ReadCloser. Using a file handle directly satisfies this requirement and avoids loading the entire file into memory.

How do I handle redirects or retries?

Most HTTP libraries (e.g., requests, axios, httpx) follow redirects by default. For retries, use middleware or libraries like Polly (C#) or backoff (Python).

Why is the Swift example using synchronous wait?

The example uses synchronous wait for simplicity. In production, use async/await (iOS 15+) or completion handlers to avoid blocking the main thread.