Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

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

Source cURL
curl -X POST https://api.openai.com/v1/fine_tuning/jobs \
  --header "Authorization: Bearer sk-1234567890" \
  --header "Content-Type: application/json" \
  --data '{"training_file":"file-1234567890", "model":"gpt-3.5-turbo", "hyperparameters":{"n_epochs":"2"}}'

Python · requests

import os
import requests

url = "https://api.openai.com/v1/fine_tuning/jobs"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "training_file": "file-1234567890",
    "model": "gpt-3.5-turbo",
    "hyperparameters": {"n_epochs": "2"}
}

response = requests.post(url, headers=headers, json=data)
if response.status_code != 200:
    print(response.text)
else:
    print(response.json())

Python · httpx

import os
import httpx

url = "https://api.openai.com/v1/fine_tuning/jobs"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "training_file": "file-1234567890",
    "model": "gpt-3.5-turbo",
    "hyperparameters": {"n_epochs": "2"}
}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    if response.status_code != 200:
        print(response.text)
    else:
        print(response.json())

Node.js · fetch

const fetch = require('node-fetch');

const url = 'https://api.openai.com/v1/fine_tuning/jobs';
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  training_file: 'file-1234567890',
  model: 'gpt-3.5-turbo',
  hyperparameters: { n_epochs: '2' }
};

fetch(url, {
  method: 'POST',
  headers: headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (!res.ok) {
      return res.text().then(text => { throw new Error(text); });
    }
    return res.json();
  })
  .then(json => console.log(json))
  .catch(err => console.error(err));

Node.js · axios

const axios = require('axios');

const url = 'https://api.openai.com/v1/fine_tuning/jobs';
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  training_file: 'file-1234567890',
  model: 'gpt-3.5-turbo',
  hyperparameters: { n_epochs: '2' }
};

axios.post(url, data, { headers })
  .then(response => {
    if (response.status !== 200) {
      console.error(response.data);
    } else {
      console.log(response.data);
    }
  })
  .catch(error => {
    console.error(error.message);
  });

Go · net/http

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	url := "https://api.openai.com/v1/fine_tuning/jobs"
	reqBody := map[string]interface{}{
		"training_file": "file-1234567890",
		"model":         "gpt-3.5-turbo",
		"hyperparameters": map[string]string{
			"n_epochs": "2",
		},
	}
	body, _ := json.Marshal(reqBody)

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

	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENAI_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

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

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Request failed: %s", string(body))
	}

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
}

PHP · cURL

<?php

$url = 'https://api.openai.com/v1/fine_tuning/jobs';
$headers = [
    'Authorization: Bearer ' . getenv('OPENAI_API_KEY'),
    'Content-Type: application/json'
];
$data = [
    'training_file' => 'file-1234567890',
    'model' => 'gpt-3.5-turbo',
    'hyperparameters' => ['n_epochs' => '2']
];

$options = [
    'http' => [
        'header' => $headers,
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    echo $response;
} else {
    echo $response;
}
?>

Ruby · net/http

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

url = URI.parse('https://api.openai.com/v1/fine_tuning/jobs')
headers = {
  'Authorization' => "Bearer #{ENV['OPENAI_API_KEY']}",
  'Content-Type' => 'application/json'
}
data = {
  training_file: 'file-1234567890',
  model: 'gpt-3.5-turbo',
  hyperparameters: { n_epochs: '2' }
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.request_uri, headers)
request.body = data.to_json

response = http.request(request)
if response.code != '200'
  puts response.body
else
  puts JSON.parse(response.body)
end

Swift · URLSession

import Foundation

let url = URL(string: "https://api.openai.com/v1/fine_tuning/jobs")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "training_file": "file-1234567890",
    "model": "gpt-3.5-turbo",
    "hyperparameters": ["n_epochs": "2"]
]

request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print(error.localizedDescription)
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print(String(data: data ?? Data(), encoding: .utf8) ?? "")
        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 reqwest::blocking::Client;
use std::collections::HashMap;
use std::env;

fn main() {
    let url = "https://api.openai.com/v1/fine_tuning/jobs";
    let client = Client::new();
    let api_key = env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set");

    let mut params = HashMap::new();
    params.insert("training_file", "file-1234567890");
    params.insert("model", "gpt-3.5-turbo");
    let mut hyperparams = HashMap::new();
    hyperparams.insert("n_epochs", "2");
    params.insert("hyperparameters", hyperparams);

    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&params)
        .send()
        .expect("Failed to send request");

    if !response.status().is_success() {
        println!("{}", response.text().expect("Failed to read response"));
    } else {
        println!("{:?}", response.json::<serde_json::Value>().unwrap());
    }
}

C# · HttpClient

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

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

        var requestBody = new Dictionary<string, object>
        {
            { "training_file", "file-1234567890" },
            { "model", "gpt-3.5-turbo" },
            { "hyperparameters", new Dictionary<string, string> { { "n_epochs", "2" } } }
        };

        var content = new StringContent(JsonSerializer.Serialize(requestBody))
        {
            MediaType = "application/json"
        };

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        var response = await client.PostAsync(url, content);

        if (!response.IsSuccessStatusCode)
        {
            var error = await response.Content.ReadAsStringAsync();
            Console.WriteLine(error);
        }
        else
        {
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

Translation notes

  • All implementations use environment variables for the API key (OPENAI_API_KEY)
  • JSON bodies are constructed as native objects/dictionaries, not raw strings
  • Error handling checks HTTP status codes and prints the response body on failure
  • Libraries used are idiomatic for each language (requests, httpx, fetch, axios, net/http, etc.)
  • Go and Rust examples use blocking clients for simplicity; async versions would be more idiomatic in production

Common pitfalls when porting

  • Forgetting to set the OPENAI_API_KEY environment variable before running the code
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Using raw strings for JSON bodies instead of proper serialization
  • Hardcoding sensitive values like API keys in the code
  • Not setting the Content-Type header to application/json
  • Assuming all responses are JSON (some APIs may return plain text 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 the API key?

Environment variables are the standard way to handle secrets in applications. They prevent accidental exposure of sensitive data in code repositories or logs.

Can I use async/await in Go or Rust examples?

Yes, but the examples use blocking clients for simplicity. In production, you should use async versions (e.g., reqwest::Client in Rust with async/await) for better performance.

How do I handle rate limits or retries?

Most HTTP libraries support interceptors or middleware for retries. For example, in Python you can use `requests` with `urllib3.util.Retry` or `httpx` with custom retry logic.

What if the API returns a non-JSON error?

Always check the response content type. If it's not JSON, read the response as plain text (e.g., using `response.text()` in Python or `response.Content.ReadAsStringAsync()` in C#).