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 '{"name":"my-custom-model","permission":[{"id":"user_id","object":"model_permission","created":1677614400}]}'

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 = {
    "name": "my-custom-model",
    "permission": [{
        "id": "user_id",
        "object": "model_permission",
        "created": 1677614400
    }]
}

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['OPENAI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "name": "my-custom-model",
    "permission": [{
        "id": "user_id",
        "object": "model_permission",
        "created": 1677614400
    }]
}

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

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

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 = {
    name: 'my-custom-model',
    permission: [{
        id: 'user_id',
        object: 'model_permission',
        created: 1677614400
    }]
};

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

Node.js · axios

const axios = require('axios');

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 = {
    name: 'my-custom-model',
    permission: [{
        id: 'user_id',
        object: 'model_permission',
        created: 1677614400
    }]
};

axios.put(url, data, { headers })
    .then(response => {
        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")
	
	data := map[string]interface{}{
		"name": "my-custom-model",
		"permission": []map[string]interface{}{
			{
				"id":     "user_id",
				"object": "model_permission",
				"created": float64(1677614400),
			},
		},
	}
	
	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 body:", err)
		return
	}

	if resp.StatusCode >= 400 {
		fmt.Println(string(body))
	} else {
		fmt.Println(string(body))
	}
}

PHP · cURL

<?php

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

$data = [
    'name' => 'my-custom-model',
    'permission' => [[
        'id' => 'user_id',
        'object' => 'model_permission',
        'created' => 1677614400
    ]]
];

$options = [
    'http' => [
        'method' => 'PUT',
        'header' => [
            "Authorization: Bearer $apiKey",
            "Content-Type: application/json"
        ],
        'content' => json_encode($data)
    ]
];

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

if ($http_response_header[0] === 'HTTP/1.1 200 OK' || strpos($http_response_header[0], '20') === 0) {
    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['OPENAI_API_KEY']

data = {
  name: 'my-custom-model',
  permission: [{
    id: 'user_id',
    object: 'model_permission',
    created: 1677614400
  }]
}

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

request = Net::HTTP::Put.new(url.path, {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json'
})

request.body = data.to_json

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"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "name": "my-custom-model",
    "permission": [
        [
            "id": "user_id",
            "object": "model_permission",
            "created": 1677614400
        ]
    ]
]

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

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
    }
    guard let data = data else {
        print("No data received")
        return
    }
    if httpResponse.statusCode >= 400 {
        if let responseString = String(data: data, encoding: .utf8) {
            print(responseString)
        }
    } else {
        if let responseString = String(data: data, encoding: .utf8) {
            print(responseString)
        }
    }
}

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

Rust · reqwest

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

#[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 headers = reqwest::header::HeaderMap::new();
    headers.insert("Authorization", format!("Bearer {}", api_key).parse()?);
    headers.insert("Content-Type", "application/json".parse()?);

    let body = json!({
        "name": "my-custom-model",
        "permission": [{
            "id": "user_id",
            "object": "model_permission",
            "created": 1677614400
        }]
    });

    let client = reqwest::Client::new();
    let response = client.put(url)
        .headers(headers)
        .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.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
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");

        var data = new
        {
            name = "my-custom-model",
            permission = new[]
            {
                new
                {
                    id = "user_id",
                    @object = "model_permission",
                    created = 1677614400
                }
            }
        };

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var content = new StringContent(JsonSerializer.Serialize(data));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.PutAsync(url, content);
        var responseBody = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(responseBody);
        }
        else
        {
            Console.WriteLine(responseBody);
        }
    }
}

Translation notes

  • All implementations use idiomatic HTTP clients for their respective languages.
  • Bearer token is read from environment variable OPENAI_API_KEY to avoid hardcoding.
  • Error handling checks HTTP status code and prints response body if >= 400.
  • JSON bodies are constructed as objects/dicts, not raw strings.
  • Go and Rust examples require async/await patterns for HTTP calls.
  • Swift example uses URLSession and runs the task in the main run loop.

Common pitfalls when porting

  • Forgetting to set Content-Type header in raw HTTP clients (e.g., Go, Rust).
  • Not properly escaping JSON body in languages with manual string construction (e.g., PHP, Ruby).
  • Ignoring SSL/TLS verification in Go or Rust (not shown here but important in production).
  • Assuming synchronous HTTP calls work in async languages (e.g., Rust, Swift).
  • Not handling environment variable absence gracefully (e.g., defaulting to empty string).

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 (e.g., in version control). They also allow easy rotation of secrets without code changes.

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

Most HTTP libraries support interceptors or middleware for retries. For example, in Python requests, you can use the `requests` library with a retry strategy, or in Go, use a custom HTTP client with retry logic.

Can I use a different JSON library in these examples?

Yes, but ensure it supports the same serialization format (e.g., camelCase vs. snake_case). For example, in Go, you might use `encoding/json`, and in Rust, `serde_json`.