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 --header "Authorization: Bearer sk_test_1234567890"

Python · requests

import os
import requests

response = requests.get(
    "https://api.stripe.com/v1/balance",
    headers={"Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}"}
)
response.raise_for_status()
print(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']}"}
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://api.stripe.com/v1/balance', {
  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/balance', {
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`
  }
});
console.log(response.data);

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	req, err := http.NewRequest("GET", "https://api.stripe.com/v1/balance", nil)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("STRIPE_SECRET_KEY"))

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

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP error! status: %s", resp.Status)
	}
	fmt.Println(resp.Body)
}

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')
]);

$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");
}

header('Content-Type: application/json');
echo $response;
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']}"

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/balance")!
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.localizedDescription)
    }
    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \(String(describing: (response as? HTTPURLResponse)?.statusCode))")
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) {
        print(json)
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest;
use std::error::Error;

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

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

    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/balance");
        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 checks HTTP status and throws/raises on failure
  • JSON responses are parsed where applicable
  • Go and Swift use standard library HTTP clients
  • Python uses both requests and httpx for variety
  • Node.js examples use modern ES modules and async/await

Common pitfalls when porting

  • Forgetting to set STRIPE_SECRET_KEY in environment
  • Not handling HTTP errors (silent failures)
  • Hardcoding secrets in source code
  • Assuming JSON response without checking Content-Type
  • Using deprecated HTTP clients in older codebases

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 instead of hardcoding secrets?

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

How do I set the STRIPE_SECRET_KEY environment variable?

In Unix-like systems: `export STRIPE_SECRET_KEY=sk_test_1234567890` (add to ~/.bashrc or ~/.zshrc for persistence). In Windows: `set STRIPE_SECRET_KEY=sk_test_1234567890` (temporary) or set via System Properties > Environment Variables.

Can I use a different HTTP client library?

Yes, but ensure it supports modern TLS, async/await (if needed), and proper error handling. Popular alternatives include Python's httpx, Node.js's undici, or Go's fasthttp for performance-critical cases.