Qaynaq LABS · TOOLS

CURL → CODE · POST · API-KEY

cURL → 10 languages

POST api.aws.amazon.com · body: json · secrets replaced with env vars.

Source cURL
curl -X POST https://api.aws.amazon.com/2016-11-15/functions/function_name/invocations \
  -H "x-amz-date: 20230101T000000Z" \
  -H "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/us-east-1/lambda/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890abcdef" \
  -d '{"payload":{"key":"value"}}'

Python · requests

import os
import requests

response = requests.post(
    f"https://api.aws.amazon.com/2016-11-15/functions/{os.environ['FUNCTION_NAME']}/invocations",
    headers={
        "x-amz-date": "20230101T000000Z",
        "Authorization": os.environ["AWS_AUTH_HEADER"]
    },
    json={"payload": {"key": "value"}}
)

if response.status_code >= 400:
    raise Exception(f"Request failed: {response.text}")

print(response.json())

Python · httpx

import os
import httpx

with httpx.Client() as client:
    response = client.post(
        f"https://api.aws.amazon.com/2016-11-15/functions/{os.environ['FUNCTION_NAME']}/invocations",
        headers={
            "x-amz-date": "20230101T000000Z",
            "Authorization": os.environ["AWS_AUTH_HEADER"]
        },
        json={"payload": {"key": "value"}}
    )

    if response.status_code >= 400:
        raise Exception(f"Request failed: {response.text}")

    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import process from 'process';

const response = await fetch(
  `https://api.aws.amazon.com/2016-11-15/functions/${process.env.FUNCTION_NAME}/invocations`,
  {
    method: 'POST',
    headers: {
      'x-amz-date': '20230101T000000Z',
      'Authorization': process.env.AWS_AUTH_HEADER
    },
    body: JSON.stringify({ payload: { key: 'value' } })
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${await response.text()}`);
}

console.log(await response.json());

Node.js · axios

import axios from 'axios';
import process from 'process';

const response = await axios.post(
  `https://api.aws.amazon.com/2016-11-15/functions/${process.env.FUNCTION_NAME}/invocations`,
  { payload: { key: 'value' } },
  {
    headers: {
      'x-amz-date': '20230101T000000Z',
      'Authorization': process.env.AWS_AUTH_HEADER
    }
  }
);

if (response.status >= 400) {
  throw new Error(`Request failed: ${response.statusText}`);
}

console.log(response.data);

Go · net/http

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	client := &http.Client{}
	url := fmt.Sprintf("https://api.aws.amazon.com/2016-11-15/functions/%s/invocations", os.Getenv("FUNCTION_NAME"))

	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		log.Fatal(err)
	}

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

	body := map[string]interface{}{
		"payload": map[string]string{"key": "value"},
	}
	bodyBytes, _ := json.Marshal(body)
	req.Body = http.NoBody
	req.GetBody = func() (io.ReadCloser, error) {
		return io.NopCloser(bytes.NewReader(bodyBytes)), nil
	}

	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		log.Fatalf("Request failed: %s", resp.Status)
	}

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
}

PHP · cURL

<?php
$ch = curl_init();

$url = sprintf(
    'https://api.aws.amazon.com/2016-11-15/functions/%s/invocations',
    urlencode(getenv('FUNCTION_NAME'))
);

$body = json_encode(['payload' => ['key' => 'value']]);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'x-amz-date: 20230101T000000Z',
    'Authorization: ' . getenv('AWS_AUTH_HEADER'),
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($httpCode >= 400) {
    throw new Exception("Request failed: " . $response);
}

print_r(json_decode($response, true));

Ruby · net/http

require 'net/http'
require 'json'
require 'uri'

uri = URI.parse("https://api.aws.amazon.com/2016-11-15/functions/#{ENV['FUNCTION_NAME']}/invocations")

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

request = Net::HTTP::Post.new(uri.request_uri)
request['x-amz-date'] = '20230101T000000Z'
request['Authorization'] = ENV['AWS_AUTH_HEADER']
request.body = { payload: { key: 'value' } }.to_json

response = http.request(request)

if response.code.to_i >= 400
  raise "Request failed: #{response.body}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.aws.amazon.com/2016-11-15/functions/" + ProcessInfo.processInfo.environment["FUNCTION_NAME"]! + "/invocations")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("20230101T000000Z", forHTTPHeaderField: "x-amz-date")
request.setValue(ProcessInfo.processInfo.environment["AWS_AUTH_HEADER"]!, forHTTPHeaderField: "Authorization")

let body: [String: Any] = ["payload": ["key": "value"]]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode < 400 else {
        fatalError("Request failed with status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    if let data = data {
        let json = try JSONSerialization.jsonObject(with: data)
        print(json)
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest::blocking::Client;
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let function_name = env::var("FUNCTION_NAME")?;
    let auth_header = env::var("AWS_AUTH_HEADER")?;

    let url = format!("https://api.aws.amazon.com/2016-11-15/functions/{}/invocations", function_name);
    let body = json!({"payload": {"key": "value"}});

    let response = client
        .post(&url)
        .header("x-amz-date", "20230101T000000Z")
        .header("Authorization", auth_header)
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed: {}", response.text()?).into());
    }

    println!("{:?}", response.json::<serde_json::Value>()?);
    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        var functionName = Environment.GetEnvironmentVariable("FUNCTION_NAME");
        var authHeader = Environment.GetEnvironmentVariable("AWS_AUTH_HEADER");

        var url = $"https://api.aws.amazon.com/2016-11-15/functions/{functionName}/invocations";
        var body = new { payload = new { key = "value" } };

        var request = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = new StringContent(JsonSerializer.Serialize(body))
            {
                Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
            }
        };

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

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed: {await response.Content.ReadAsStringAsync()}");
        }

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

Translation notes

  • Python: Using requests for simplicity; httpx is async-first.
  • Node: Using modern ES modules (import/export).
  • Go: Manual JSON marshaling for body; uses environment variables.
  • PHP: Uses curl extension; body is JSON-encoded.
  • Ruby: Uses Net::HTTP; body is JSON-encoded.
  • Swift: Uses URLSession; requires RunLoop for async execution.
  • Rust: Uses reqwest blocking client; serde_json for body.
  • C#: Uses HttpClient; System.Text.Json for serialization.

Common pitfalls when porting

  • Go: Manual body handling is verbose; prefer higher-level libraries like resty.
  • PHP: Ensure curl extension is enabled; error handling is minimal.
  • Swift: URLSession is async; RunLoop.main.run() is a simplification.
  • Rust: reqwest blocking client is not suitable for production; use async.
  • C#: HttpClient should be reused; not disposed per request.

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?

AWS credentials and signed headers should never be hardcoded. They are typically generated dynamically using AWS SDKs or tools like aws-signature-v4.

Can I use async/await in Python with httpx?

Yes. Replace the synchronous code with async/await using httpx.AsyncClient and asyncio.run().

How do I handle pagination or retries in these examples?

These examples are minimal. Use libraries like tenacity (Python), axios-retry (Node), or Polly (.NET) for retries. Pagination is request-specific.