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/invoices/in_1234567890abcdef --header "Authorization: Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc"

Python · requests

import os
import requests

url = "https://api.stripe.com/v1/invoices/in_1234567890abcdef"
headers = {
    "Authorization": f"Bearer {os.environ.get('STRIPE_SECRET_KEY')}"
}

response = requests.get(url, headers=headers)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

url = "https://api.stripe.com/v1/invoices/in_1234567890abcdef"
headers = {
    "Authorization": f"Bearer {os.environ.get('STRIPE_SECRET_KEY')}"
}

with httpx.Client() as client:
    response = client.get(url, headers=headers)
    response.raise_for_status()
    print(response.json())

Node.js · fetch

const fetch = require('node-fetch');

const url = 'https://api.stripe.com/v1/invoices/in_1234567890abcdef';
const headers = {
  'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`
};

fetch(url, { headers })
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Node.js · axios

const axios = require('axios');

const url = 'https://api.stripe.com/v1/invoices/in_1234567890abcdef';
const headers = {
  'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`
};

axios.get(url, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Error:', error.response.status, error.response.data);
    } else {
      console.error('Error:', error.message);
    }
  });

Go · net/http

package main

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

func main() {
	url := "https://api.stripe.com/v1/invoices/in_1234567890abcdef"
	client := &http.Client{}
	
	req, err := http.NewRequest("GET", url, 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 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("HTTP error! status: %s, body: %s", resp.Status, body)
	}
	
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	
	fmt.Println(string(body))
}

PHP · cURL

<?php

$url = 'https://api.stripe.com/v1/invoices/in_1234567890abcdef';
$headers = [
    'Authorization: Bearer ' . getenv('STRIPE_SECRET_KEY')
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

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

curl_close($ch);
?>

Ruby · net/http

require 'net/http'
require 'json'

url = URI.parse('https://api.stripe.com/v1/invoices/in_1234567890abcdef')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Get.new(url)
request['Authorization'] = "Bearer #{ENV['STRIPE_SECRET_KEY']}"

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.stripe.com/v1/invoices/in_1234567890abcdef")!
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 {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \(httpResponse.statusCode)")
        if let data = data, let body = String(data: data, encoding: .utf8) {
            print("Body: \(body)")
        }
        return
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.stripe.com/v1/invoices/in_1234567890abcdef";
    let client = reqwest::Client::new();
    
    let response = client
        .get(url)
        .header("Authorization", format!("Bearer {}", env::var("STRIPE_SECRET_KEY")?))
        .send()
        .await?;
    
    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await?;
        eprintln!("HTTP error! status: {}, body: {}", status, body);
        std::process::exit(1);
    }
    
    let json: serde_json::Value = response.json().await?;
    println!("{}", json);
    
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var url = "https://api.stripe.com/v1/invoices/in_1234567890abcdef";
        var client = new HttpClient();
        
        client.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue(
                "Bearer", 
                Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY")
            );
        
        var response = await client.GetAsync(url);
        
        if (!response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"HTTP error! status: {response.StatusCode}, body: {content}");
            return;
        }
        
        var json = await response.Content.ReadAsStringAsync();
        Console.WriteLine(json);
    }
}

Translation notes

  • All implementations use environment variables for secrets (STRIPE_SECRET_KEY).
  • Error handling checks HTTP status codes and reads response bodies on failure.
  • JSON responses are parsed into native objects where applicable.
  • Go and Rust require async/await for HTTP calls.
  • Swift uses URLSession for idiomatic iOS/macOS networking.
  • PHP uses cURL for HTTP requests as it's the most common library.

Common pitfalls when porting

  • Forgetting to set the environment variable STRIPE_SECRET_KEY before running.
  • Not handling HTTP errors properly (e.g., ignoring status codes).
  • In Rust, missing the tokio runtime for async operations.
  • In Swift, forgetting to call RunLoop.main.run() in a non-async context.
  • In PHP, not checking curl_errno() for cURL errors.
  • In Go, not closing the response body (defer resp.Body.Close()).

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 are the standard way to handle secrets in applications. They prevent secrets from being hardcoded in source code and allow for easy configuration changes without modifying the code.

How do I set the STRIPE_SECRET_KEY environment variable?

For local development, you can set it in your shell: `export STRIPE_SECRET_KEY=sk_test_4eC39HqLyjWDarjtT1zdp7dc` (Linux/macOS) or `$env:STRIPE_SECRET_KEY="sk_test_4eC39HqLyjWDarjtT1zdp7dc"` (Windows PowerShell). For production, use a secrets manager or deployment configuration.

Why does the Rust example use tokio?

The reqwest library in Rust is async by default. The tokio runtime is required to run async code in a synchronous context (like the main function).

How do I handle pagination in the Stripe API?

The Stripe API uses cursor-based pagination. You can use the `starting_after` or `ending_before` parameters in subsequent requests. Libraries like Stripe's official SDKs handle this automatically.