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 --header "Authorization: Bearer sk-abc123" --header "Content-Type: application/json" --data '{"prompt":"Explain quantum computing","max_tokens":150}'

Python · requests

import os
import requests

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

response = requests.put(url, headers=headers, json=data)
if response.status_code >= 400:
    print(response.text)
else:
    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.get('OPENAI_API_KEY')}",
    "Content-Type": "application/json"
}
data = {
    "prompt": "Explain quantum computing",
    "max_tokens": 150
}

with httpx.Client() as client:
    response = client.put(url, headers=headers, json=data)
    if response.status_code >= 400:
        print(response.text)
    else:
        print(response.json())

Node.js · fetch

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

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

try {
  const response = await fetch(url, {
    method: 'PUT',
    headers,
    body: JSON.stringify(data)
  });
  if (response.status >= 400) {
    console.log(await response.text());
  } else {
    console.log(await response.json());
  }
} catch (error) {
  console.error(error);
}

Node.js · axios

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

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

try {
  const response = await axios.put(url, data, { headers });
  if (response.status >= 400) {
    console.log(response.data);
  } else {
    console.log(response.data);
  }
} catch (error) {
  console.error(error);
}

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")
	if apiKey == "" {
		fmt.Println("OPENAI_API_KEY environment variable not set")
		return
	}

	data := map[string]interface{}{
		"prompt":      "Explain quantum computing",
		"max_tokens":  150,
	}
	body, _ := json.Marshal(data)

	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(body))
	if err != nil {
		fmt.Println(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(err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
	} else {
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
	}
}

PHP · cURL

<?php

$url = 'https://api.openai.com/v1/models/text-davinci-003';
$apiKey = getenv('OPENAI_API_KEY');
if (empty($apiKey)) {
    die('OPENAI_API_KEY environment variable not set');
}

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

$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] >= 400) {
    echo $response;
} else {
    echo $response;
}

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.fetch('OPENAI_API_KEY')

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

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 = body

response = http.request(request)

if response.code.to_i >= 400
  puts response.body
else
  puts response.body
end

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"

let apiKey = ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? ""
if apiKey.isEmpty {
    print("OPENAI_API_KEY environment variable not set")
    exit(1)
}

request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

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

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: body)
} catch {
    print("Failed to serialize body: \(error)")
    exit(1)
}

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print(error)
        return
    }

    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }

    if httpResponse.statusCode >= 400 {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    } else {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    }
}

task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest;
use std::collections::HashMap;
use std::env;

#[tokio::main]
async 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 mut body = HashMap::new();
    body.insert("prompt", "Explain quantum computing");
    body.insert("max_tokens", "150");

    let client = reqwest::Client::new();
    let response = client
        .put(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&body)
        .send()
        .await?;

    if response.status().as_u16() >= 400 {
        println!("{}", response.text().await?);
    } else {
        println!("{}", response.text().await?);
    }

    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(string[] args)
    {
        var url = "https://api.openai.com/v1/models/text-davinci-003";
        var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("OPENAI_API_KEY environment variable not set");
            return;
        }

        var body = new Dictionary<string, object>
        {
            { "prompt", "Explain quantum computing" },
            { "max_tokens", 150 }
        };

        using var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Put, url)
        {
            Content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("data", Newtonsoft.Json.JsonConvert.SerializeObject(body)) })
        };
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.SendAsync(request);
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        else
        {
            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.
  • Error handling checks status code >= 400 and prints the response body.
  • JSON bodies are constructed as objects/dictionaries, not raw strings.
  • Minimal error handling is present but not exhaustive (e.g., network errors may propagate).

Common pitfalls when porting

  • Forgetting to set the OPENAI_API_KEY environment variable will cause failures.
  • In C#, the body serialization approach is simplified; consider using StringContent with JSON for better fidelity.
  • In Go, the response body must be closed to avoid resource leaks.
  • In Swift, the URLSession task runs asynchronously; ensure the RunLoop is active.
  • In Rust, the reqwest client requires the tokio runtime for async operations.
  • In PHP, the stream context approach may not handle redirects or complex responses well.

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 instead of hardcoding?

Environment variables prevent accidental exposure of secrets in version control or logs. They also allow different configurations across environments (dev, staging, prod).

Why is the C# example using FormUrlEncodedContent for JSON?

The example simplifies the body construction. For better fidelity, use StringContent with JSON serialization (e.g., System.Text.Json).

How do I handle rate limits or retries in these examples?

The examples focus on minimal error handling. For production, consider adding retry logic (e.g., exponential backoff) and rate limit handling using libraries like Polly (C#), tenacity (Python), or custom middleware.