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/balance \
  -H "Authorization: Bearer sk_test_1234567890" \
  -H "Stripe-Version: 2023-10-16"

Python · requests

import os
import requests

response = requests.get(
    "https://api.stripe.com/v1/balance",
    headers={
        "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
        "Stripe-Version": "2023-10-16"
    }
)
response.raise_for_status()
balance = response.json()

Python · httpx

import os
import httpx

with httpx.Client() as client:
    response = client.get(
        "https://api.stripe.com/v1/balance",
        headers={
            "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
            "Stripe-Version": "2023-10-16"
        }
    )
    response.raise_for_status()
    balance = response.json()

Node.js · fetch

import fetch from 'node-fetch';

const balance = await fetch('https://api.stripe.com/v1/balance', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
    'Stripe-Version': '2023-10-16'
  }
}).then(res => {
  if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
  return res.json();
});

Node.js · axios

import axios from 'axios';

const balance = await axios.get('https://api.stripe.com/v1/balance', {
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
    'Stripe-Version': '2023-10-16'
  }
}).then(res => res.data).catch(err => {
  throw new Error(`Request failed: ${err.message}`);
});

Go · net/http

package main

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

func main() {
	req, err := http.NewRequest("GET", "https://api.stripe.com/v1/balance", nil)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+os.Getenv("STRIPE_SECRET_KEY"))
	req.Header.Set("Stripe-Version", "2023-10-16")

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

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("HTTP error! status: %d, body: %s", resp.StatusCode, body))
	}

	balance := make(map[string]interface{})
	if err := json.NewDecoder(resp.Body).Decode(&balance); err != nil {
		panic(err)
	}
	fmt.Println(balance)
}

PHP · cURL

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/balance');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('STRIPE_SECRET_KEY'),
    'Stripe-Version: 2023-10-16'
]);

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

$balance = json_decode($response, true);
var_dump($balance);

curl_close($ch);

Ruby · net/http

require 'net/http'
require 'json'

uri = URI('https://api.stripe.com/v1/balance')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{ENV['STRIPE_SECRET_KEY']}"
req['Stripe-Version'] = '2023-10-16'

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

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

balance = JSON.parse(res.body)
puts balance

Swift · URLSession

import Foundation

let url = URL(string: "https://api.stripe.com/v1/balance")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["STRIPE_SECRET_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("2023-10-16", forHTTPHeaderField: "Stripe-Version")

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

Rust · reqwest

use std::env;
use reqwest;
use serde_json::Value;

#[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/balance")
        .header("Authorization", format!("Bearer {}", env::var("STRIPE_SECRET_KEY")?))
        .header("Stripe-Version", "2023-10-16")
        .send()
        .await?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await?;
        return Err(format!("HTTP error! status: {}, body: {}", status, body).into());
    }

    let balance: Value = response.json().await?;
    println!("{:?}", balance);
    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.Add("Stripe-Version", "2023-10-16");
        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/balance");
        if (!response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            throw new Exception($"HTTP error! status: {response.StatusCode}, body: {content}");
        }

        var balance = await response.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>();
        Console.WriteLine(balance);
    }
}

Translation notes

  • All implementations use environment variables for secrets (STRIPE_SECRET_KEY)
  • Error handling checks HTTP status and reads response body on failure
  • JSON responses are parsed into native objects/dictionaries
  • Headers are set in the idiomatic way for each language
  • Go and Rust examples use async/await where applicable

Common pitfalls when porting

  • Forgetting to set the Stripe-Version header may cause API version mismatches
  • Not reading the response body on failure can hide error details
  • Hardcoding secrets in code instead of using environment variables
  • Ignoring SSL/TLS verification in Go or other low-level clients
  • Assuming the response is always JSON without checking Content-Type

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?

Environment variables separate configuration from code, reducing the risk of secret leakage in version control or logs. They also allow easy switching between different environments (dev, staging, prod).

How do I handle pagination in Stripe API?

Stripe API responses include a 'has_more' boolean and a 'data' array. Use the 'starting_after' or 'ending_before' query parameters to fetch subsequent pages. Example: /v1/balance?starting_after=txn_123

What if I need to send a POST request with a JSON body?

Replace the method with POST, add a 'Content-Type: application/json' header, and include the body as a JSON object. Example in Python: requests.post(url, json={'key': 'value'}, headers={...})