Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

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

Source cURL
curl -X POST https://api.stripe.com/v1/invoices/in_1234567890/pay \
  -H "Authorization: Bearer sk_test_1234567890" \
  -H "Stripe-Version: 2023-10-16"

Python · requests

import os
import requests

url = "https://api.stripe.com/v1/invoices/in_1234567890/pay"
headers = {
    "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
    "Stripe-Version": "2023-10-16"
}

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

Python · httpx

import os
import httpx

url = "https://api.stripe.com/v1/invoices/in_1234567890/pay"
headers = {
    "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
    "Stripe-Version": "2023-10-16"
}

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

Node.js · fetch

import fetch from 'node-fetch';
import process from 'process';

const url = new URL('https://api.stripe.com/v1/invoices/in_1234567890/pay');
const headers = {
  'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
  'Stripe-Version': '2023-10-16'
};

try {
  const response = await fetch(url, { method: 'POST', headers });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error('Error:', error);
}

Node.js · axios

import axios from 'axios';
import process from 'process';

const url = 'https://api.stripe.com/v1/invoices/in_1234567890/pay';
const headers = {
  'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
  'Stripe-Version': '2023-10-16'
};

try {
  const response = await axios.post(url, null, { headers });
  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"
	"log"
	"net/http"
	"os"
)

func main() {
	url := "https://api.stripe.com/v1/invoices/in_1234567890/pay"
	client := &http.Client{}

	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		log.Fatal(err)
	}

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

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

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("Unexpected status code: %d", resp.StatusCode)
	}

	// Assuming JSON response
	// var result map[string]interface{}
	// json.NewDecoder(resp.Body).Decode(&result)
	// fmt.Println(result)
	fmt.Println("Request successful")
}

PHP · cURL

<?php

$url = 'https://api.stripe.com/v1/invoices/in_1234567890/pay';
$headers = [
    'Authorization: Bearer ' . getenv('STRIPE_SECRET_KEY'),
    'Stripe-Version: 2023-10-16'
];

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

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

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

Ruby · net/http

require 'net/http'
require 'json'
require 'uri'

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

request = Net::HTTP::Post.new(url.path)
request['Authorization'] = "Bearer #{ENV['STRIPE_SECRET_KEY']}"
request['Stripe-Version'] = '2023-10-16'

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.stripe.com/v1/invoices/in_1234567890/pay")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
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
    if let error = error {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("HTTP error: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}
task.resume()

// Run in a context that supports async (e.g., Swift Concurrency)
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 url = "https://api.stripe.com/v1/invoices/in_1234567890/pay";
    let stripe_key = env::var("STRIPE_SECRET_KEY")?;

    let client = reqwest::Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", stripe_key))
        .header("Stripe-Version", "2023-10-16")
        .send()
        .await?;

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

    let 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_1234567890/pay";
        var stripeKey = Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY");

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {stripeKey}");
        client.DefaultRequestHeaders.Add("Stripe-Version", "2023-10-16");

        var response = await client.PostAsync(url, null);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error: {response.StatusCode}");
        }

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

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/throws on failure.
  • JSON response is parsed and printed (commented in Go where decoding is shown).
  • Go example uses standard library; others use popular third-party libraries where idiomatic.
  • Swift example uses URLSession and requires async context (RunLoop for simplicity).

Common pitfalls when porting

  • Forgetting to set the Stripe-Version header may cause API version mismatches.
  • Not handling environment variable absence (STRIPE_SECRET_KEY) will cause runtime errors.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the example requires an async context; synchronous usage may block the main thread.
  • In Rust, the reqwest client requires async runtime (tokio in this case).
  • In PHP, curl_setopt must be set for POST method explicitly.

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.

How do I handle pagination or large responses?

Use streaming or chunked responses where supported by the library (e.g., httpx in Python, reqwest in Rust).

Can I use a different HTTP client in Go?

Yes, but the standard library is idiomatic for most use cases. Alternatives like 'github.com/go-resty/resty' are also popular.

Why is the Go example commented for JSON parsing?

The example focuses on the HTTP request. JSON parsing is shown as a comment for clarity; uncomment and adjust as needed.

How do I add a request body to this POST?

Add a body parameter to the request (e.g., in Python: `requests.post(url, json={...}, headers=headers)`).