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/files \
  -H "Authorization: Bearer sk-1234567890" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@example.json" -F "purpose=fine-tune"

Python · requests

import os
import requests

url = "https://api.openai.com/v1/files"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "multipart/form-data"
}
files = {
    "file": open("example.json", "rb"),
    "purpose": (None, "fine-tune")
}

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/files"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "multipart/form-data"
}
files = {
    "file": open("example.json", "rb"),
    "purpose": (None, "fine-tune")
}

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

Node.js · fetch

import fetch from 'node-fetch';
import fs from 'fs';
import { Buffer } from 'buffer';

const url = 'https://api.openai.com/v1/files';
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
  'Content-Type': 'multipart/form-data'
};

const formData = new FormData();
formData.append('file', fs.createReadStream('example.json'));
formData.append('purpose', 'fine-tune');

fetch(url, {
  method: 'POST',
  headers: headers,
  body: formData
})
  .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

import axios from 'axios';
import fs from 'fs';
import FormData from 'form-data';

const url = 'https://api.openai.com/v1/files';
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
};

const form = new FormData();
form.append('file', fs.createReadStream('example.json'));
form.append('purpose', 'fine-tune');

axios.post(url, form, { headers: { ...headers, ...form.getHeaders() } })
  .then(res => {
    if (res.status !== 200) throw new Error(`HTTP error! status: ${res.status}`);
    console.log(res.data);
  })
  .catch(err => console.error(err));

Go · net/http

package main

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

func main() {
	url := "https://api.openai.com/v1/files"
	apiKey := os.Getenv("OPENAI_API_KEY")
	
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	
	file, err := os.Open("example.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	
	part, err := writer.CreateFormFile("file", "example.json")
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(part, file)
	if err != nil {
		panic(err)
	}
	
	_ = writer.WriteField("purpose", "fine-tune")
	writer.Close()
	
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", 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("HTTP error! status: %s", resp.Status))
	}
	
	bodyBytes, _ := io.ReadAll(resp.Body)
	fmt.Println(string(bodyBytes))
}

PHP · cURL

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

$boundary = uniqid();
$headers = [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: multipart/form-data; boundary=' . $boundary
];

$body = '';
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Disposition: form-data; name="file"; filename="example.json"' . "\r\n";
$body .= "\r\n";
$body .= file_get_contents('example.json') . "\r\n";
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Disposition: form-data; name="purpose"' . "\r\n";
$body .= "\r\n";
$body .= 'fine-tune' . "\r\n";
$body .= '--' . $boundary . '--' . "\r\n";

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

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

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

print_r(json_decode($response, true));
?>

Ruby · net/http

require 'net/http'
require 'uri'
require 'mime/types'

url = URI.parse('https://api.openai.com/v1/files')
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, {
  file: UploadIO.new(File.open('example.json'), 'application/json'),
  purpose: 'fine-tune'
})
request['Authorization'] = "Bearer #{api_key}"

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.openai.com/v1/files")!
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()

// Add file part
let fileData = try Data(contentsOf: URL(fileURLWithPath: "example.json"))
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"example.json\"\r\n".data(using: .utf8)!)
body.append("Content-Type: application/json\r\n\r\n".data(using: .utf8)!)
body.append(fileData)
body.append("\r\n".data(using: .utf8)!)

// Add purpose part
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"purpose\"\r\n\r\n".data(using: .utf8)!)
body.append("fine-tune".data(using: .utf8)!)
body.append("\r\n".data(using: .utf8)!)

// Close boundary
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 else {
        print("Invalid response")
        return
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \(httpResponse.statusCode)")
        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;
use reqwest::multipart;
use reqwest::blocking::Client;

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

    let file_data = fs::read("example.json")?;

    let form = multipart::Form::new()
        .file("file", "example.json")?
        .text("purpose", "fine-tune");

    let client = Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .multipart(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.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var url = "https://api.openai.com/v1/files";
        var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");

        using var client = new HttpClient();
        using var form = new MultipartFormDataContent();

        var fileContent = new StreamContent(File.OpenRead("example.json"));
        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
        form.Add(fileContent, "file", "example.json");
        form.Add(new StringContent("fine-tune"), "purpose");

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

        var response = await client.PostAsync(url, form);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {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 is opened and streamed where possible to avoid loading entire file into memory.
  • Python implementations use requests and httpx, both widely used libraries.

Common pitfalls when porting

  • Forgetting to set the Content-Type header for multipart requests can cause failures.
  • Not properly closing file handles or streams can lead to resource leaks.
  • In Go, forgetting to call writer.Close() before sending the request will cause the request to fail.
  • In Swift, the URLSession task must be started with task.resume().
  • In Rust, using reqwest::blocking requires a blocking runtime; async version would need async/await.
  • In PHP, manually constructing multipart boundaries can be error-prone; consider using a library.

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 easy rotation of secrets without changing code.

How do I handle large files in multipart requests?

Stream the file content rather than loading it entirely into memory. Most libraries support streaming via file handles or streams.

Why does the Swift example use RunLoop.main.run()?

Swift's URLSession tasks are asynchronous. In a command-line app, RunLoop.main.run() keeps the program running to allow the async task to complete.