Qaynaq LABS · TOOLS

CURL → CODE · PUT · BEARER

cURL → 10 languages

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

Source cURL
curl -X PUT https://api.stripe.com/v1/customers/cus_ABC1234567890 \
  --header "Authorization: Bearer sk_test_1234567890" \
  --data "name=John Doe" \
  --data "email=john.doe@example.com"

Python · requests

import os
import requests

url = "https://api.stripe.com/v1/customers/cus_ABC1234567890"
headers = {
    "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}"
}
data = {
    "name": "John Doe",
    "email": "john.doe@example.com"
}

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

Python · httpx

import os
import httpx

url = "https://api.stripe.com/v1/customers/cus_ABC1234567890"
headers = {
    "Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}"
}
data = {
    "name": "John Doe",
    "email": "john.doe@example.com"
}

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

Node.js · fetch

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

const url = new URL('https://api.stripe.com/v1/customers/cus_ABC1234567890');
const headers = {
  'Authorization': `Bearer ${env.STRIPE_SECRET_KEY}`
};
const body = new URLSearchParams({
  name: 'John Doe',
  email: 'john.doe@example.com'
});

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

Node.js · axios

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

const url = 'https://api.stripe.com/v1/customers/cus_ABC1234567890';
const headers = {
  'Authorization': `Bearer ${env.STRIPE_SECRET_KEY}`
};
const data = new URLSearchParams({
  name: 'John Doe',
  email: 'john.doe@example.com'
});

const response = await axios.put(url, data, { headers });
console.log(response.data);

Go · net/http

package main

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

func main() {
	apiKey := os.Getenv("STRIPE_SECRET_KEY")
	if apiKey == "" {
		panic("STRIPE_SECRET_KEY environment variable not set")
	}

	baseURL := "https://api.stripe.com/v1/customers/cus_ABC1234567890"
	u, _ := url.Parse(baseURL)

	client := &http.Client{}
	req, _ := http.NewRequest("PUT", u.String(), nil)
	req.Header.Set("Authorization", "Bearer "+apiKey)

	form := url.Values{}
	form.Add("name", "John Doe")
	form.Add("email", "john.doe@example.com")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Body = http.NoBody
	req.GetBody = func() (io.ReadCloser, error) {
		return io.NopCloser(strings.NewReader(form.Encode())), nil
	}

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

	if resp.StatusCode >= 400 {
		panic(fmt.Sprintf("HTTP error! status: %s", resp.Status))
	}

	var result map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		panic(err)
	}
	fmt.Println(result)
}

PHP · cURL

<?php

$url = 'https://api.stripe.com/v1/customers/cus_ABC1234567890';
$apiKey = getenv('STRIPE_SECRET_KEY');
if (empty($apiKey)) {
    die('STRIPE_SECRET_KEY environment variable not set');
}

$headers = [
    'Authorization: Bearer ' . $apiKey
];

$data = [
    'name' => 'John Doe',
    'email' => 'john.doe@example.com'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Curl error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode >= 400) {
    die("HTTP error! status: $httpCode");
}

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

Ruby · net/http

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

url = URI.parse('https://api.stripe.com/v1/customers/cus_ABC1234567890')
api_key = ENV.fetch('STRIPE_SECRET_KEY')

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

request = Net::HTTP::Put.new(url.path)
request['Authorization'] = "Bearer #{api_key}"
request.set_form_data({
  'name' => 'John Doe',
  'email' => 'john.doe@example.com'
})

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

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

let apiKey = ProcessInfo.processInfo.environment["STRIPE_SECRET_KEY"] ?? ""
if apiKey.isEmpty {
    fatalError("STRIPE_SECRET_KEY environment variable not set")
}
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")

let body = "name=John Doe&email=john.doe@example.com"
request.httpBody = body.data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    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::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = env::var("STRIPE_SECRET_KEY")?;
    let url = "https://api.stripe.com/v1/customers/cus_ABC1234567890";

    let mut headers = header::HeaderMap::new();
    headers.insert(
        header::AUTHORIZATION,
        header::HeaderValue::from_str(&format!("Bearer {}", api_key))?,
    );

    let mut form = HashMap::new();
    form.insert("name", "John Doe");
    form.insert("email", "john.doe@example.com");

    let client = Client::new();
    let response = client
        .put(url)
        .headers(headers)
        .form(&form)
        .send()?;

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

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

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var apiKey = Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            throw new Exception("STRIPE_SECRET_KEY environment variable not set");
        }

        var url = "https://api.stripe.com/v1/customers/cus_ABC1234567890";
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

        var formData = new Dictionary<string, string>
        {
            {"name", "John Doe"},
            {"email", "john.doe@example.com"}
        };

        var response = await client.PutAsync(url, new FormUrlEncodedContent(formData));
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! 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.
  • Form data is sent as application/x-www-form-urlencoded.
  • Error handling checks HTTP status and throws/panics on failure.
  • JSON response is parsed and printed where applicable.

Common pitfalls when porting

  • Forgetting to set STRIPE_SECRET_KEY environment variable will cause runtime errors.
  • In Go, manually handling form data requires careful encoding to avoid issues.
  • In Swift, URLSession is asynchronous; the example uses RunLoop.main.run() for simplicity in a script context.
  • In Rust, using reqwest::blocking requires a synchronous runtime; async versions are more common in production.
  • In PHP, ensure curl is installed and enabled in the PHP environment.

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, avoiding hardcoding sensitive data in source code and enabling secure deployment practices.

Can I use JSON instead of form data?

Yes, but the original cURL uses --data which sends form data. To send JSON, change the Content-Type header to application/json and send a JSON body.

How do I handle pagination or large responses?

Most HTTP clients provide streaming or chunked response handling. Check the library documentation for your language for large response handling.