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/invoiceitems?limit=10 \
  -H "Authorization: Bearer sk_test_1234567890" \
  -H "Content-Type: application/json"

Python · requests

import os
import requests

response = requests.get(
    "https://api.stripe.com/v1/invoiceitems",
    params={"limit": 10},
    headers={
        "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
        "Content-Type": "application/json"
    }
)
response.raise_for_status()

Python · httpx

import os
import httpx

with httpx.Client() as client:
    response = client.get(
        "https://api.stripe.com/v1/invoiceitems",
        params={"limit": 10},
        headers={
            "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
            "Content-Type": "application/json"
        }
    )
    response.raise_for_status()

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://api.stripe.com/v1/invoiceitems?limit=10', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
    'Content-Type': 'application/json'
  }
});

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();

Node.js · axios

import axios from 'axios';

const response = await axios.get('https://api.stripe.com/v1/invoiceitems', {
  params: { limit: 10 },
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
    'Content-Type': 'application/json'
  }
});

if (response.status !== 200) {
  throw new Error(`Request failed with status ${response.status}`);
}

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	req, err := http.NewRequest("GET", "https://api.stripe.com/v1/invoiceitems?limit=10", nil)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", os.Getenv("STRIPE_SECRET_KEY")))
	req.Header.Set("Content-Type", "application/json")

	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("Request failed with status %d: %s", resp.StatusCode, string(body)))
	}
}

PHP · cURL

<?php

$ch = curl_init();

$url = 'https://api.stripe.com/v1/invoiceitems?limit=10';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('STRIPE_SECRET_KEY'),
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode !== 200) {
    throw new Exception("Request failed with status $httpCode: $response");
}

curl_close($ch);
$json = json_decode($response, true);

Ruby · net/http

require 'net/http'
require 'json'

uri = URI('https://api.stripe.com/v1/invoiceitems')
uri.query = URI.encode_www_form({ limit: 10 })

req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{ENV['STRIPE_SECRET_KEY']}"
req['Content-Type'] = 'application/json'

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

unless res.is_a?(Net::HTTPSuccess)
  raise "Request failed with status #{res.code}: #{res.body}"
end

JSON.parse(res.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.stripe.com/v1/invoiceitems?limit=10")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["STRIPE_SECRET_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

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

Rust · reqwest

use reqwest;
use std::env;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = reqwest::Client::new();
    let response = client
        .get("https://api.stripe.com/v1/invoiceitems")
        .query(&[("limit", "10")])
        .header("Authorization", format!("Bearer {}", env::var("STRIPE_SECRET_KEY").unwrap()))
        .header("Content-Type", "application/json")
        .send()
        .await?;

    if !response.status().is_success() {
        panic!("Request failed with status: {}", response.status());
    }

    let _body = response.json::<serde_json::Value>().await?;
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Get, "https://api.stripe.com/v1/invoiceitems?limit=10");
        request.Headers.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY")}");
        request.Headers.Add("Content-Type", "application/json");

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed with status {response.StatusCode}");
        }

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

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variable STRIPE_SECRET_KEY to avoid hardcoding.
  • Error handling checks HTTP status code and raises an exception if not successful.
  • Query parameters are passed via the params/query builder of each library.
  • Headers are set using the standard header mechanisms of each library.

Common pitfalls when porting

  • Forgetting to set the Content-Type header (though not strictly required for GET requests).
  • Not handling environment variable absence (STRIPE_SECRET_KEY) which will cause runtime errors.
  • Ignoring SSL/TLS verification in Go or other languages where it might be disabled by default.
  • Assuming the response body is always JSON without checking Content-Type header.
  • Using synchronous HTTP clients in async contexts (e.g., Swift's URLSession in a non-async context).

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?

Environment variables separate configuration from code, preventing accidental exposure of secrets in version control or logs. They also allow different configurations across environments (dev, staging, prod).

Can I use a different HTTP client library in these languages?

Yes, but the examples use the most idiomatic and widely adopted libraries for simplicity and maintainability. Swapping libraries may require adjustments in syntax and error handling.

How do I handle pagination in the response?

The response body typically includes a 'has_more' flag and a 'data' array. Use the 'starting_after' or 'ending_before' query parameters to fetch subsequent pages. Example: `?limit=10&starting_after=<last_id>`.