Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST api.openai.com · body: multipart · secrets replaced with env vars.

Source cURL
curl -X POST https://api.openai.com/v1/images/variations \
  -H "Authorization: Bearer sk-ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" \
  -H "Content-Type: multipart/form-data" \
  -F "image=@/path/to/image.png" \
  -F "n=1" \
  -F "size=1024x1024"

Python · requests

import os
import requests

url = "https://api.openai.com/v1/images/variations"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "multipart/form-data"
}
files = {
    "image": open("/path/to/image.png", "rb"),
    "n": (None, "1"),
    "size": (None, "1024x1024")
}

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

Python · httpx

import os
import httpx

url = "https://api.openai.com/v1/images/variations"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "multipart/form-data"
}
files = {
    "image": open("/path/to/image.png", "rb"),
    "n": (None, "1"),
    "size": (None, "1024x1024")
}

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

Node.js · fetch

const fetch = require('node-fetch');
const FormData = require('form-data');
const fs = require('fs');

const url = 'https://api.openai.com/v1/images/variations';
const form = new FormData();
form.append('image', fs.createReadStream('/path/to/image.png'));
form.append('n', '1');
form.append('size', '1024x1024');

fetch(url, {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        ...form.getHeaders()
    },
    body: form
})
.then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));

Node.js · axios

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const url = 'https://api.openai.com/v1/images/variations';
const form = new FormData();
form.append('image', fs.createReadStream('/path/to/image.png'));
form.append('n', '1');
form.append('size', '1024x1024');

axios.post(url, form, {
    headers: {
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        ...form.getHeaders()
    }
})
.then(response => {
    console.log(response.data);
})
.catch(error => {
    console.error(error);
});

Go · net/http

package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	url := "https://api.openai.com/v1/images/variations"
	apiKey := os.Getenv("OPENAI_API_KEY")
	
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	
	file, err := os.Open("/path/to/image.png")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	
	part, err := writer.CreateFormFile("image", file.Name())
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(part, file)
	if err != nil {
		panic(err)
	}
	
	_ = writer.WriteField("n", "1")
	_ = writer.WriteField("size", "1024x1024")
	
	writer.Close()
	
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	
	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("request failed with status: %s", resp.Status))
	}
	
	bodyBytes, _ := io.ReadAll(resp.Body)
	fmt.Println(string(bodyBytes))
}

PHP · cURL

<?php
$url = 'https://api.openai.com/v1/images/variations';
$apiKey = getenv('OPENAI_API_KEY');

$client = new CURLClient();
$client->setOption(CURLOPT_URL, $url);
$client->setOption(CURLOPT_POST, true);
$client->setOption(CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $apiKey,
]);

$boundary = uniqid();
$client->setOption(CURLOPT_HTTPHEADER, array_merge(
    $client->getInfo(CURLINFO_HEADER_OUT, true),
    ['Content-Type: multipart/form-data; boundary=' . $boundary]
));

$postFields = [
    'image' => new CURLFile('/path/to/image.png', 'image/png'),
    'n' => '1',
    'size' => '1024x1024'
];

$client->setOption(CURLOPT_POSTFIELDS, $postFields);

$response = $client->execute();
if ($response === false) {
    die('Error: ' . $client->getError());
}

$httpCode = $client->getInfo(CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    die("HTTP error: $httpCode");
}

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

$client->close();

class CURLClient {
    private $ch;
    
    public function __construct() {
        $this->ch = curl_init();
    }
    
    public function setOption($option, $value) {
        curl_setopt($this->ch, $option, $value);
    }
    
    public function getInfo($option) {
        return curl_getinfo($this->ch, $option);
    }
    
    public function execute() {
        return curl_exec($this->ch);
    }
    
    public function getError() {
        return curl_error($this->ch);
    }
    
    public function close() {
        curl_close($this->ch);
    }
}
?>

Ruby · net/http

require 'net/http'
require 'uri'
require 'mimemagic'

url = URI.parse('https://api.openai.com/v1/images/variations')
api_key = ENV['OPENAI_API_KEY']

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

request = Net::HTTP::Post::Multipart.new(url.path, {
  'image' => UploadIO.new(File.open('/path/to/image.png'), 'image/png'),
  'n' => '1',
  'size' => '1024x1024'
})

request['Authorization'] = "Bearer #{api_key}"

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.openai.com/v1/images/variations")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")

let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

var body = Data()

let imageData = try Data(contentsOf: URL(fileURLWithPath: "/path/to/image.png"))
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n".data(using: .utf8)!)
body.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
body.append(imageData)
body.append("\r\n".data(using: .utf8)!)

body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"n\"\r\n\r\n".data(using: .utf8)!)
body.append("1\r\n".data(using: .utf8)!)

body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"size\"\r\n\r\n".data(using: .utf8)!)
body.append("1024x1024\r\n".data(using: .utf8)!)

body.append("--\(boundary)--\r\n".data(using: .utf8)!)

request.httpBody = body

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()
RunLoop.main.run()

Rust · reqwest

use std::env;
use std::fs::File;
use std::io::Read;
use reqwest::multipart;
use reqwest::blocking::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.openai.com/v1/images/variations";
    let api_key = env::var("OPENAI_API_KEY")?;
    
    let client = Client::new();
    
    let file = File::open("/path/to/image.png")?;
    let form = multipart::Form::new()
        .file("image", "/path/to/image.png")?
        .text("n", "1")
        .text("size", "1024x1024");
    
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .multipart(form)
        .send()?;
    
    if !response.status().is_success() {
        return Err(format!("HTTP error: {}", response.status()).into());
    }
    
    let body = response.text()?;
    println!("{}", body);
    
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var url = "https://api.openai.com/v1/images/variations";
        var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
        
        using var client = new HttpClient();
        using var form = new MultipartFormDataContent();
        
        var fileStream = File.OpenRead("/path/to/image.png");
        var streamContent = new StreamContent(fileStream);
        var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync());
        form.Add(fileContent, "image", "image.png");
        
        form.Add(new StringContent("1"), "n");
        form.Add(new StringContent("1024x1024"), "size");
        
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
        
        var response = await client.PostAsync(url, form);
        
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error: {response.StatusCode}");
        }
        
        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from environment variable OPENAI_API_KEY to avoid hardcoding.
  • Multipart form data is constructed using language-specific utilities.
  • Error handling checks HTTP status and raises/throws on failure.
  • File path is hardcoded for simplicity; in production, use configurable paths.

Common pitfalls when porting

  • Forgetting to set Content-Type header for multipart requests can cause server-side issues.
  • Not closing file handles or streams can lead to resource leaks (especially in Go, Python, and Ruby).
  • In Swift, the RunLoop.main.run() is required to keep the async task alive in a command-line context.
  • In Rust, using blocking client requires careful handling in async contexts; prefer async runtime in real apps.
  • In PHP, CURLFile requires PHP 5.5+ and proper file handling to avoid errors.

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, reducing the risk of accidental exposure in version control or logs. They also allow different deployments to use different credentials without code changes.

How do I handle large file uploads efficiently?

Use streaming where possible (e.g., Python requests with file objects, Go with io.Reader, Rust with reqwest's streaming). Avoid loading entire files into memory.

Can I use async/await in all languages?

Most modern languages support async/await (Python, Node.js, Swift, Rust, C#). For others (PHP, Ruby), use threading or synchronous clients. Go uses goroutines for concurrency.