Qaynaq LABS · TOOLS

CURL → CODE · GET · BASIC

cURL → 10 languages

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

Source cURL
curl -X GET https://api.stripe.com/v1/customers/cus_123456789 -u sk_test_4eC39HqLyjWDarjtT1zdp7dc:

Python · requests

import os
import requests

url = "https://api.stripe.com/v1/customers/cus_123456789"
auth = (os.environ["STRIPE_SECRET_KEY"], "")

response = requests.get(url, auth=auth)

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

print(response.json())

Python · httpx

import os
import httpx

url = "https://api.stripe.com/v1/customers/cus_123456789"
auth = (os.environ["STRIPE_SECRET_KEY"], "")

with httpx.Client() as client:
    response = client.get(url, auth=auth)

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

    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'process';

const url = new URL('https://api.stripe.com/v1/customers/cus_123456789');

const response = await fetch(url, {
  method: 'GET',
  headers: {
    'Authorization': `Basic ${Buffer.from(`${env.STRIPE_SECRET_KEY}:`).toString('base64')}`
  }
});

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

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

Node.js · axios

import axios from 'axios';
import { env } from 'process';

const url = 'https://api.stripe.com/v1/customers/cus_123456789';

try {
  const response = await axios.get(url, {
    auth: {
      username: env.STRIPE_SECRET_KEY
    }
  });

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

  console.log(response.data);
} catch (error) {
  console.error('Error:', error.message);
}

Go · net/http

package main

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

func main() {
	url := "https://api.stripe.com/v1/customers/cus_123456789"
	apiKey := os.Getenv("STRIPE_SECRET_KEY")
	
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}

	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(apiKey+":"))
	req.Header.Set("Authorization", auth)

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

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		fmt.Printf("Request failed with status %d: %s\n", resp.StatusCode, string(body))
		return
	}

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

PHP · cURL

<?php

$url = 'https://api.stripe.com/v1/customers/cus_123456789';
$apiKey = getenv('STRIPE_SECRET_KEY');

$context = stream_context_create([
    'http' => [
        'header' => "Authorization: Basic " . base64_encode($apiKey . ':'),
    ],
]);

$response = file_get_contents($url, false, $context);

if ($http_response_header[0] === 'HTTP/1.1 400' || strpos($http_response_header[0], '40') === 0) {
    throw new Exception("Request failed: " . $response);
}

print($response);

Ruby · net/http

require 'net/http'
require 'json'
require 'base64'

url = URI.parse('https://api.stripe.com/v1/customers/cus_123456789')
api_key = ENV['STRIPE_SECRET_KEY']

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

request = Net::HTTP::Get.new(url)
request.basic_auth(api_key, '')

response = http.request(request)

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.stripe.com/v1/customers/cus_123456789")!
var request = URLRequest(url: url)
request.httpMethod = "GET"

let apiKey = ProcessInfo.processInfo.environment["STRIPE_SECRET_KEY"] ?? ""
let authString = "Basic \(apiKey):"
request.setValue(authString, 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, httpResponse.statusCode >= 400 else {
        print("Request failed with status \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }

    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) {
        print(json)
    }
}

task.resume()
sleep(1)

Rust · reqwest

use std::env;
use reqwest::blocking::Client;
use reqwest::blocking::Response;

fn main() {
    let url = "https://api.stripe.com/v1/customers/cus_123456789";
    let api_key = env::var("STRIPE_SECRET_KEY").expect("STRIPE_SECRET_KEY must be set");

    let client = Client::new();
    let response: Response = client
        .get(url)
        .basic_auth(api_key, Some(""))
        .send()
        .expect("Failed to send request");

    if !response.status().is_success() {
        eprintln!("Request failed with status: {}", response.status());
        eprintln!("{}", response.text().unwrap_or_default());
        return;
    }

    println!("{}", response.text().unwrap());
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var url = "https://api.stripe.com/v1/customers/cus_123456789";
        var apiKey = Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY");

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{apiKey}:"))
        );

        var response = await client.GetAsync(url);

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            throw new Exception($"Request failed with status {response.StatusCode}: {errorContent}");
        }

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

Translation notes

  • Basic auth is used with the secret key as the username and empty password
  • Environment variable STRIPE_SECRET_KEY is used to store the API key
  • All implementations handle basic error checking (status code >= 400)
  • JSON response is parsed/printed where applicable
  • Go and Rust use blocking clients for simplicity; async variants are available

Common pitfalls when porting

  • Forgetting to set the STRIPE_SECRET_KEY environment variable
  • Incorrectly encoding the basic auth credentials (e.g., forgetting the colon)
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • In Swift, the task runs asynchronously; the sleep(1) is a placeholder for actual async handling
  • In PHP, file_get_contents may not be suitable for all environments (e.g., disabled allow_url_fopen)

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 password empty in basic auth?

Stripe's API expects the secret key as the username in Basic Auth, with an empty password. This is a common pattern for API keys.

Can I use Bearer token instead of Basic Auth?

Stripe's API primarily uses Basic Auth with the secret key. Bearer tokens are typically used for publishable keys or OAuth tokens.

How do I handle pagination or large responses?

Most HTTP libraries support streaming or chunked responses. For large JSON, use streaming parsers or libraries like `httpx` in Python with `stream=True`.

Why does the Swift code use sleep(1)?

The Swift code uses a blocking approach for simplicity. In a real app, you'd use async/await with URLSession.dataTaskPublisher or Combine.