Qaynaq LABS · TOOLS

CURL → CODE · DELETE · BEARER

cURL → 10 languages

DELETE api.openai.com · secrets replaced with env vars.

Source cURL
curl -X DELETE https://api.openai.com/v1/models/model_id \
  -H "Authorization: Bearer sk-1234567890" \
  -H "Content-Type: application/json"

Python · requests

import os
import requests

model_id = os.environ.get("MODEL_ID")
url = f"https://api.openai.com/v1/models/{model_id}"
headers = {
    "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}",
    "Content-Type": "application/json"
}

response = requests.delete(url, headers=headers)
response.raise_for_status()

Python · httpx

import os
import httpx

model_id = os.environ.get("MODEL_ID")
url = f"https://api.openai.com/v1/models/{model_id}"
headers = {
    "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}",
    "Content-Type": "application/json"
}

with httpx.Client() as client:
    response = client.delete(url, headers=headers)
    response.raise_for_status()

Node.js · fetch

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

const modelId = process.env.MODEL_ID;
const url = `https://api.openai.com/v1/models/${modelId}`;
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
  'Content-Type': 'application/json'
};

fetch(url, { method: 'DELETE', headers })
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  });

Node.js · axios

import axios from 'axios';
import process from 'process';

const modelId = process.env.MODEL_ID;
const url = `https://api.openai.com/v1/models/${modelId}`;
const headers = {
  'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
  'Content-Type': 'application/json'
};

axios.delete(url, { headers })
  .then(response => {
    if (response.status >= 400) throw new Error(`HTTP error! status: ${response.status}`);
  });

Go · net/http

package main

import (
	"fmt"
	"net/http"
	"os"
)

func main() {
	modelId := os.Getenv("MODEL_ID")
	url := fmt.Sprintf("https://api.openai.com/v1/models/%s", modelId)
	
	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		panic(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 {
		panic(err)
	}
	defer resp.Body.Close()
	
	if resp.StatusCode >= 400 {
		panic(fmt.Sprintf("HTTP error! status: %d", resp.StatusCode))
	}
}

PHP · cURL

<?php
$modelId = getenv('MODEL_ID');
$url = 'https://api.openai.com/v1/models/' . $modelId;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('OPENAI_API_KEY'),
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    throw new Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode >= 400) {
    throw new Exception("HTTP error! status: $httpCode");
}

Ruby · net/http

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

model_id = ENV.fetch('MODEL_ID')
url = URI.parse("https://api.openai.com/v1/models/#{model_id}")

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

request = Net::HTTP::Delete.new(url.request_uri)
request['Authorization'] = "Bearer #{ENV.fetch('OPENAI_API_KEY')}"
request['Content-Type'] = 'application/json'

response = http.request(request)
raise "HTTP error! status: #{response.code}" unless response.is_a?(Net::HTTPSuccess)

Swift · URLSession

import Foundation

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

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError(error.localizedDescription)
    }
    guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest;
use std::env;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let model_id = env::var("MODEL_ID").expect("MODEL_ID must be set");
    let api_key = env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set");
    
    let url = format!("https://api.openai.com/v1/models/{}", model_id);
    let client = reqwest::Client::new();
    
    let response = client
        .delete(&url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .send()
        .await?;
    
    if !response.status().is_success() {
        panic!("HTTP error! status: {}", response.status());
    }
    
    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var modelId = Environment.GetEnvironmentVariable("MODEL_ID");
        var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
        
        var client = new HttpClient();
        var url = $"https://api.openai.com/v1/models/{modelId}";
        
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
        client.DefaultRequestHeaders.Add("Content-Type", "application/json");
        
        var response = await client.DeleteAsync(url);
        
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }
    }
}

Translation notes

  • Bearer token is read from OPENAI_API_KEY environment variable
  • MODEL_ID is read from MODEL_ID environment variable
  • All implementations use idiomatic HTTP clients for their language
  • Error handling checks HTTP status code >= 400 as failure
  • No request body is sent (DELETE with no body)
  • URL path includes MODEL_ID as a path parameter

Common pitfalls when porting

  • Forgetting to set MODEL_ID or OPENAI_API_KEY environment variables
  • Using hardcoded bearer tokens instead of environment variables
  • Ignoring SSL/TLS verification (not shown here but important in production)
  • Assuming DELETE requests always return 200 OK (some APIs return 204 No Content)
  • Not handling async/await properly in languages that require it (e.g., Swift, Rust, C#)

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 different configurations across environments (dev, staging, prod) without code changes.

What if the API returns a non-200 status code for a successful DELETE?

Check the API documentation. Some APIs return 204 No Content for successful DELETEs. Adjust the success check accordingly (e.g., `response.statusCode >= 200 && response.statusCode < 300`).

How do I handle the response body in these examples?

The examples focus on the DELETE request. To read the response body, add `.text()` in Python (requests/httpx), `.then(res => res.text())` in Node.js, `response.Content.ReadAsStringAsync()` in C#, etc. Always check the status code first.

Why is the URL constructed with string interpolation instead of a URL builder?

String interpolation is idiomatic in many languages for simple URL construction. For complex URLs, consider using language-specific URL builders (e.g., `URL` in Python, `Uri` in C#, `NSURL` in Swift).

Can I use a different HTTP client library?

Yes, but prefer idiomatic libraries. For example, in Python, `httpx` is more modern than `requests`; in Go, `net/http` is standard; in Rust, `reqwest` is popular. Avoid low-level libraries unless necessary.