Qaynaq LABS · TOOLS

CURL → CODE · GET · BEARER

cURL → 10 languages

GET api.stripe.com · secrets replaced with env vars.

Source cURL
curl -X GET https://api.stripe.com/v1/charges/ch_1234567890 \
  -H "Authorization: Bearer sk_test_1234567890"

Python · requests

import os
import requests

response = requests.get(
    "https://api.stripe.com/v1/charges/ch_1234567890",
    headers={"Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

response = httpx.get(
    "https://api.stripe.com/v1/charges/ch_1234567890",
    headers={"Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}"}
)
response.raise_for_status()
print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://api.stripe.com/v1/charges/ch_1234567890', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`
  }
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log(data);

Node.js · axios

import axios from 'axios';

const response = await axios.get('https://api.stripe.com/v1/charges/ch_1234567890', {
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`
  }
});
console.log(response.data);

Go · net/http

package main

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

func main() {
	req, err := http.NewRequest("GET", "https://api.stripe.com/v1/charges/ch_1234567890", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("STRIPE_SECRET_KEY"))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("HTTP error! status: %d", resp.StatusCode))
	}

	// Handle response body as needed
}

PHP · cURL

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com/v1/charges/ch_1234567890");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer " . getenv("STRIPE_SECRET_KEY")
]);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    throw new Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    throw new Exception("HTTP error! status: " . $httpCode);
}

$data = json_decode($response, true);
print_r($data);

curl_close($ch);
?>

Ruby · net/http

require 'net/http'
require 'json'

uri = URI('https://api.stripe.com/v1/charges/ch_1234567890')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{ENV['STRIPE_SECRET_KEY']}"

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

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

puts JSON.parse(res.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.stripe.com/v1/charges/ch_1234567890")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["STRIPE_SECRET_KEY"] ?? "")", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let response = client
        .get("https://api.stripe.com/v1/charges/ch_1234567890")
        .header("Authorization", format!("Bearer {}", env::var("STRIPE_SECRET_KEY")?))
        .send()
        .await?;

    if !response.status().is_success() {
        panic!("HTTP error! status: {}", response.status());
    }

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

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
            "Bearer",
            Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY")
        );

        var response = await client.GetAsync("https://api.stripe.com/v1/charges/ch_1234567890");
        response.EnsureSuccessStatusCode();

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

Translation notes

  • All implementations use environment variables for secrets (STRIPE_SECRET_KEY).
  • Error handling is minimal but checks HTTP status and raises exceptions where appropriate.
  • JSON response is parsed into native data structures where possible.
  • Go and Rust examples require async/await or event loop handling for non-blocking execution.
  • Swift example uses URLSession and requires a run loop to execute the async task.

Common pitfalls when porting

  • Forgetting to set the environment variable STRIPE_SECRET_KEY before running the code.
  • Not handling HTTP errors properly (e.g., ignoring status codes).
  • In Rust, forgetting to add reqwest and tokio dependencies to Cargo.toml.
  • In Swift, not running the task in a run loop (e.g., in a command-line tool).
  • In PHP, not checking for cURL errors or HTTP status codes.
  • In Go, not properly closing the response body or handling errors in HTTP requests.

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 use environment variables for secrets instead of hardcoding them?

Environment variables are a secure way to handle secrets as they are not committed to version control and can be easily managed in different environments (e.g., development, staging, production).

How do I install the required dependencies for each language?

Each language has its own package manager or build system. For example, Python uses pip (requests, httpx), Node.js uses npm (node-fetch, axios), Go uses go get, PHP uses Composer, Ruby uses Bundler, Swift uses Swift Package Manager, Rust uses Cargo, and C# uses NuGet.

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

In a command-line Swift application, the URLSession task is asynchronous. RunLoop.main.run() keeps the program running to allow the async task to complete. In a real iOS/macOS app, this is handled by the app's run loop automatically.

How do I handle pagination or large responses in these examples?

Most HTTP libraries provide methods to stream or paginate responses. For example, in Python (requests/httpx), you can use response.iter_lines() for streaming. In Go, you can use io.Copy() to stream the response body. In Rust, you can use response.bytes().await for streaming.