Qaynaq LABS · TOOLS

CURL → CODE · PUT · BEARER

cURL → 10 languages

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

Source cURL
curl -X PUT https://api.openai.com/v1/models/text-davinci-003 \
  -H "Authorization: Bearer sk-1234567890" \
  -H "Content-Type: application/json" \
  -d '{"prompt":"Explain quantum computing","max_tokens":100}'

Python · requests

import os
import requests

url = "https://api.openai.com/v1/models/text-davinci-003"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "prompt": "Explain quantum computing",
    "max_tokens": 100
}

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

Python · httpx

import os
import httpx

url = "https://api.openai.com/v1/models/text-davinci-003"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "prompt": "Explain quantum computing",
    "max_tokens": 100
}

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

Node.js · fetch

import fetch from 'node-fetch';
import * as process from 'process';

const url = 'https://api.openai.com/v1/models/text-davinci-003';
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  prompt: 'Explain quantum computing',
  max_tokens: 100
};

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

Node.js · axios

import axios from 'axios';
import * as process from 'process';

const url = 'https://api.openai.com/v1/models/text-davinci-003';
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  prompt: 'Explain quantum computing',
  max_tokens: 100
};

axios.put(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

Go · net/http

package main

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

func main() {
	url := "https://api.openai.com/v1/models/text-davinci-003"
	apiKey := os.Getenv("OPENAI_API_KEY")
	
	data := map[string]interface{}{
		"prompt":     "Explain quantum computing",
		"max_tokens": 100,
	}
	
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}
	
	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()
	
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}
	
	if resp.StatusCode >= 400 {
		fmt.Printf("HTTP error! status: %s\n", resp.Status)
		fmt.Println(string(body))
		return
	}
	
	fmt.Println(string(body))
}

PHP · cURL

<?php

$url = 'https://api.openai.com/v1/models/text-davinci-003';
$apiKey = getenv('OPENAI_API_KEY');

$data = [
    'prompt' => 'Explain quantum computing',
    'max_tokens' => 100
];

$options = [
    'http' => [
        'method' => 'PUT',
        'header' => [
            "Authorization: Bearer $apiKey",
            "Content-Type: application/json"
        ],
        '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') {
    throw new Exception("HTTP error! status: " . $http_response_header[0]);
}

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

Ruby · net/http

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

url = URI.parse('https://api.openai.com/v1/models/text-davinci-003')
api_key = ENV['OPENAI_API_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['Content-Type'] = 'application/json'

request.body = {
  prompt: 'Explain quantum computing',
  max_tokens: 100
}.to_json

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/models/text-davinci-003")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "prompt": "Explain quantum computing",
    "max_tokens": 100
]

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

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error.localizedDescription)")
        return
    }
    
    guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
        print("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

task.resume()

// Keep the program running to allow the async task to complete
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest::blocking::Client;
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.openai.com/v1/models/text-davinci-003";
    let api_key = env::var("OPENAI_API_KEY")?;
    
    let client = Client::new();
    let response = client
        .put(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&json!({
            "prompt": "Explain quantum computing",
            "max_tokens": 100
        }))
        .send()?;
    
    if !response.status().is_success() {
        eprintln!("HTTP error! status: {}", response.status());
        return Ok(());
    }
    
    let body = response.text()?;
    println!("{}", body);
    
    Ok(())
}

C# · HttpClient

using System;
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/models/text-davinci-003";
        var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
        
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        
        var data = new {
            prompt = "Explain quantum computing",
            max_tokens = 100
        };
        
        var response = await client.PutAsJsonAsync(url, data);
        
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"HTTP error! status: {response.StatusCode}");
            return;
        }
        
        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

Translation notes

  • All implementations use environment variables for secrets (OPENAI_API_KEY)
  • JSON bodies are sent as objects/dicts, not raw strings
  • Error handling checks HTTP status codes and raises/throws on failure
  • Libraries used are idiomatic for each language (requests, httpx, fetch, axios, net/http, etc.)

Common pitfalls when porting

  • Forgetting to set the environment variable OPENAI_API_KEY before running the code
  • Not handling async/await properly in languages that require it (Swift, Rust, C#)
  • Using raw strings for JSON bodies instead of proper object serialization
  • Ignoring SSL/TLS verification (not an issue in these examples as libraries handle it by default)
  • Assuming the API returns JSON without checking Content-Type headers

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 are a secure way to handle secrets as they are not committed to version control and can be managed separately from the code.

How do I install the required dependencies for each language?

Each language has its own package manager: pip for Python, npm for Node.js, composer for PHP, bundler for Ruby, Swift Package Manager for Swift, cargo for Rust, and NuGet for C#.

What if the API returns a non-JSON response?

Check the Content-Type header of the response. If it's not JSON, parse the response body accordingly (e.g., as plain text or XML).

How do I handle rate limits or retries?

Implement retry logic with exponential backoff. Libraries like axios and httpx have built-in retry mechanisms, or you can write custom logic using timers and loops.