Qaynaq LABS · TOOLS

CURL → CODE · GET · API-KEY

cURL → 10 languages

GET s3.amazonaws.com · secrets replaced with env vars.

Source cURL
curl -X GET https://s3.amazonaws.com/bucket-name/object-key.txt \
  -H "x-amz-date: 20230101T000000Z" \
  -H "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890abcdef"

Python · requests

import os
import requests

url = "https://s3.amazonaws.com/bucket-name/object-key.txt"
headers = {
    "x-amz-date": "20230101T000000Z",
    "Authorization": os.environ.get("AWS_AUTHORIZATION")
}

response = requests.get(url, headers=headers)
response.raise_for_status()
print(response.text)

Python · httpx

import os
import httpx

url = "https://s3.amazonaws.com/bucket-name/object-key.txt"
headers = {
    "x-amz-date": "20230101T000000Z",
    "Authorization": os.environ.get("AWS_AUTHORIZATION")
}

with httpx.Client() as client:
    response = client.get(url, headers=headers)
    response.raise_for_status()
    print(response.text)

Node.js · fetch

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

const url = 'https://s3.amazonaws.com/bucket-name/object-key.txt';
const headers = {
  'x-amz-date': '20230101T000000Z',
  'Authorization': process.env.AWS_AUTHORIZATION
};

fetch(url, { method: 'GET', headers })
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return response.text();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Node.js · axios

const axios = require('axios');

const url = 'https://s3.amazonaws.com/bucket-name/object-key.txt';
const headers = {
  'x-amz-date': '20230101T000000Z',
  'Authorization': process.env.AWS_AUTHORIZATION
};

axios.get(url, { headers })
  .then(response => {
    if (response.status !== 200) throw new Error(`HTTP error! status: ${response.status}`);
    console.log(response.data);
  })
  .catch(error => console.error('Error:', error));

Go · net/http

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	url := "https://s3.amazonaws.com/bucket-name/object-key.txt"
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("x-amz-date", "20230101T000000Z")
	req.Header.Set("Authorization", os.Getenv("AWS_AUTHORIZATION"))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Printf("HTTP error! status: %d\n", resp.StatusCode)
		return
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}
	fmt.Println(string(body))
}

PHP · cURL

<?php

$url = 'https://s3.amazonaws.com/bucket-name/object-key.txt';
$headers = [
    'x-amz-date: 20230101T000000Z',
    'Authorization: ' . getenv('AWS_AUTHORIZATION')
];

$ch = curl_init($url);
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);

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

echo $response;

Ruby · net/http

require 'net/http'
require 'uri'

url = URI.parse('https://s3.amazonaws.com/bucket-name/object-key.txt')
req = Net::HTTP::Get.new(url)
req['x-amz-date'] = '20230101T000000Z'
req['Authorization'] = ENV['AWS_AUTHORIZATION']

res = Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
  http.request(req)
end

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

puts res.body

Swift · URLSession

import Foundation

let url = URL(string: "https://s3.amazonaws.com/bucket-name/object-key.txt")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("20230101T000000Z", forHTTPHeaderField: "x-amz-date")
request.setValue(ProcessInfo.processInfo.environment["AWS_AUTHORIZATION"], forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \(httpResponse.statusCode)")
        return
    }
    if let data = data, let body = String(data: data, encoding: .utf8) {
        print(body)
    }
}
task.resume()

// Keep the program running to allow async task to complete
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://s3.amazonaws.com/bucket-name/object-key.txt";
    let authorization = env::var("AWS_AUTHORIZATION")?;

    let client = reqwest::Client::new();
    let response = client
        .get(url)
        .header("x-amz-date", "20230101T000000Z")
        .header("Authorization", authorization)
        .send()
        .await?;

    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).into());
    }

    let body = response.text().await?;
    println!("{}", body);
    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var url = "https://s3.amazonaws.com/bucket-name/object-key.txt";
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Get, url);

        request.Headers.Add("x-amz-date", "20230101T000000Z");
        request.Headers.Add("Authorization", Environment.GetEnvironmentVariable("AWS_AUTHORIZATION"));

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

        var body = await response.Content.ReadAsStringAsync();
        Console.WriteLine(body);
    }
}

Translation notes

  • All implementations use environment variables for sensitive headers (AWS_AUTHORIZATION).
  • The cURL command uses AWS Signature v4, which is handled by the Authorization header. The actual signature generation is not shown as it is typically handled by AWS SDKs or libraries.
  • Error handling checks HTTP status codes and raises exceptions/errors when non-2xx responses are received.
  • Python (requests/httpx), Node.js (fetch/axios), Go, PHP, Ruby, Swift, Rust, and C# use idiomatic HTTP clients for their respective ecosystems.
  • The Swift example uses async/await and requires the program to run in an environment that supports it (e.g., main thread with RunLoop).

Common pitfalls when porting

  • Forgetting to set the Authorization header via environment variable will cause authentication failures.
  • Not handling HTTP errors (non-2xx responses) can lead to silent failures or incorrect data processing.
  • In Swift, forgetting to call RunLoop.main.run() in a command-line tool will cause the program to exit before the async task completes.
  • In Rust, the reqwest client requires the tokio runtime for async operations.
  • In PHP, curl_setopt must be used correctly to set headers and ensure the response is returned as a string.
  • In Go, the http.Client.Do method must be used with proper error handling for the request and response.

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

Storing sensitive headers like AWS Authorization tokens in environment variables is a security best practice. It avoids hardcoding secrets in source code and allows for easier rotation of credentials without changing the code.

Can I use AWS SDKs instead of raw HTTP requests?

Yes, AWS SDKs (e.g., boto3 for Python, AWS SDK for JavaScript, AWS SDK for Go) abstract away the low-level HTTP requests and handle authentication (including AWS Signature v4) automatically. However, this example focuses on raw HTTP requests to match the cURL command.

Why does the Swift example use RunLoop.main.run()?

In a Swift command-line tool, the program exits immediately after launching the async task unless the run loop is kept alive. RunLoop.main.run() ensures the program waits for the async network request to complete.