Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST api.stripe.com · body: form · secrets replaced with env vars.

Source cURL
curl -X POST https://api.stripe.com/v1/refunds \
  -H "Authorization: Bearer sk_test_1234567890" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "charge=ch_1234567890" \
  -d "amount=1000"

Python · requests

import os
import requests

response = requests.post(
    "https://api.stripe.com/v1/refunds",
    headers={
        "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data={
        "charge": "ch_1234567890",
        "amount": "1000"
    }
)

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

with httpx.Client() as client:
    response = client.post(
        "https://api.stripe.com/v1/refunds",
        headers={
            "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
            "Content-Type": "application/x-www-form-urlencoded"
        },
        data={
            "charge": "ch_1234567890",
            "amount": "1000"
        }
    )

    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 response = await fetch('https://api.stripe.com/v1/refunds', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${env.STRIPE_SECRET_KEY}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({
    charge: 'ch_1234567890',
    amount: '1000'
  })
});

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 response = await axios.post('https://api.stripe.com/v1/refunds', new URLSearchParams({
  charge: 'ch_1234567890',
  amount: '1000'
}), {
  headers: {
    'Authorization': `Bearer ${env.STRIPE_SECRET_KEY}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

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

console.log(response.data);

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	form := url.Values{}
	form.Add("charge", "ch_1234567890")
	form.Add("amount", "1000")

	req, err := http.NewRequest(
		"POST",
		"https://api.stripe.com/v1/refunds",
		strings.NewReader(form.Encode()),
	)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+os.Getenv("STRIPE_SECRET_KEY"))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

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

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

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

PHP · cURL

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/refunds');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'charge' => 'ch_1234567890',
    'amount' => '1000'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('STRIPE_SECRET_KEY'),
    'Content-Type: application/x-www-form-urlencoded'
]);

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

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

print_r(json_decode($response, true));

Ruby · net/http

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

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

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{ENV['STRIPE_SECRET_KEY']}"
request['Content-Type'] = 'application/x-www-form-urlencoded'
request.set_form_data({
  charge: 'ch_1234567890',
  amount: '1000'
})

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/refunds")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["STRIPE_SECRET_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let body = "charge=ch_1234567890&amount=1000"
request.httpBody = body.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        fatalError("Request failed: \(error?.localizedDescription ?? "Unknown error")")
    }

    if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
        fatalError("Request failed with status \(httpResponse.statusCode): \(String(data: data, encoding: .utf8) ?? "")")
    }

    if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

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

Rust · reqwest

use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        format!("Bearer {}", env::var("STRIPE_SECRET_KEY")?).parse()?,
    );
    headers.insert(
        "Content-Type",
        "application/x-www-form-urlencoded".parse()?,
    );

    let mut form = HashMap::new();
    form.insert("charge", "ch_1234567890");
    form.insert("amount", "1000");

    let response = client
        .post("https://api.stripe.com/v1/refunds")
        .headers(headers)
        .form(&form)
        .send()?;

    if !response.status().is_success() {
        return Err(format!(
            "Request failed with status {}: {}",
            response.status(),
            response.text()?
        ).into());
    }

    println!("{:?}", response.json::<serde_json::Value>()?);
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        var formData = new Dictionary<string, string>
        {
            {"charge", "ch_1234567890"},
            {"amount", "1000"}
        };

        var request = new HttpRequestMessage(HttpMethod.Post, "https://api.stripe.com/v1/refunds")
        {
            Content = new FormUrlEncodedContent(formData)
        };

        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
            "Bearer",
            Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY")
        );

        var response = await client.SendAsync(request);

        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

  • All implementations use the idiomatic HTTP client for the language.
  • Bearer token is read from environment variable STRIPE_SECRET_KEY.
  • Form data is sent as application/x-www-form-urlencoded.
  • Error handling checks HTTP status code and raises an exception on failure.
  • JSON response is parsed and printed in all examples.

Common pitfalls when porting

  • Forgetting to set Content-Type header for form data.
  • Not reading the bearer token from environment variables (security risk).
  • Ignoring HTTP status codes and assuming success.
  • Using raw strings for JSON bodies instead of proper serialization.
  • Not handling SSL/TLS properly in lower-level clients.

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 a secure way to handle secrets as they are not hardcoded in the source and can be managed separately from the application code.

Can I use a different HTTP client library?

Yes, but ensure it supports the same features (headers, form data, SSL/TLS) and idiomatic error handling.

How do I handle rate limits or retries?

Most HTTP clients support interceptors or middleware for retries. For rate limits, check response headers and implement exponential backoff.