Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

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

Source cURL
curl -X POST https://api.github.com/user/repos \
  -H "Authorization: token ghp_abcdefghijklmnopqrstuvwxyz1234567890" \
  -H "Accept: application/vnd.github+json" \
  -d '{"name": "my-new-repo", "private": false, "description": "A new repository created via API"}'

Python · requests

import os
import requests

url = "https://api.github.com/user/repos"
headers = {
    "Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github+json"
}
data = {
    "name": "my-new-repo",
    "private": False,
    "description": "A new repository created via API"
}

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

Python · httpx

import os
import httpx

url = "https://api.github.com/user/repos"
headers = {
    "Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github+json"
}
data = {
    "name": "my-new-repo",
    "private": False,
    "description": "A new repository created via API"
}

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

Node.js · fetch

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

const url = 'https://api.github.com/user/repos';
const headers = {
  'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github+json'
};
const data = {
  name: 'my-new-repo',
  private: false,
  description: 'A new repository created via API'
};

fetch(url, {
  method: 'POST',
  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 process from 'process';

const url = 'https://api.github.com/user/repos';
const headers = {
  'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github+json'
};
const data = {
  name: 'my-new-repo',
  private: false,
  description: 'A new repository created via API'
};

axios.post(url, data, { headers })
  .then(res => {
    console.log(res.data);
  })
  .catch(err => {
    console.error(err.message);
  });

Go · net/http

package main

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

type Repo struct {
	Name        string `json:"name"`
	Private     bool   `json:"private"`
	Description string `json:"description"`
}

func main() {
	url := "https://api.github.com/user/repos"
	token := os.Getenv("GITHUB_TOKEN")
	if token == "" {
		fmt.Println("GITHUB_TOKEN environment variable not set")
		return
	}

	data := Repo{
		Name:        "my-new-repo",
		Private:     false,
		Description: "A new repository created via API",
	}
	body, _ := json.Marshal(data)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Accept", "application/vnd.github+json")
	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()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		fmt.Printf("Request failed with status %d: %s\n", resp.StatusCode, string(body))
		return
	}

	body, _ = io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

PHP · cURL

<?php

$url = 'https://api.github.com/user/repos';
$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
    die('GITHUB_TOKEN environment variable not set');
}

$data = [
    'name' => 'my-new-repo',
    'private' => false,
    'description' => 'A new repository created via API'
];

$options = [
    'http' => [
        'method' => 'POST',
        'header' => [
            'Authorization: Bearer ' . $token,
            'Accept: application/vnd.github+json',
            'Content-Type: application/json'
        ],
        'content' => json_encode($data)
    ]
];

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

if ($result === false) {
    $error = error_get_last();
    die('Request failed: ' . $error['message']);
}

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

Ruby · net/http

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

url = URI.parse('https://api.github.com/user/repos')
token = ENV.fetch('GITHUB_TOKEN') { raise 'GITHUB_TOKEN environment variable not set' }

data = {
  name: 'my-new-repo',
  private: false,
  description: 'A new repository created via API'
}

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

request = Net::HTTP::Post.new(url.path, {
  'Authorization' => "Bearer #{token}",
  'Accept' => 'application/vnd.github+json',
  'Content-Type' => 'application/json'
})
request.body = data.to_json

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  puts "Request failed with status #{response.code}: #{response.body}"
  exit 1
end

puts response.body

Swift · URLSession

import Foundation

let url = URL(string: "https://api.github.com/user/repos")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "name": "my-new-repo",
    "private": false,
    "description": "A new repository created via API"
]

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)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("Request failed with 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()
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.github.com/user/repos";
    let token = env::var("GITHUB_TOKEN")?;

    let client = Client::new();
    let body = json!({
        "name": "my-new-repo",
        "private": false,
        "description": "A new repository created via API"
    });

    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", token))
        .header("Accept", "application/vnd.github+json")
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        eprintln!("Request failed with status: {}", response.status());
        return Ok(());
    }

    let json: serde_json::Value = response.json()?;
    println!("{}", json);
    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.github.com/user/repos";
        var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
        if (string.IsNullOrEmpty(token))
        {
            Console.WriteLine("GITHUB_TOKEN environment variable not set");
            return;
        }

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

        var data = new
        {
            name = "my-new-repo",
            @private = false,
            description = "A new repository created via API"
        };

        var response = await client.PostAsJsonAsync(url, data);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Request failed with status {response.StatusCode}");
            return;
        }

        var json = await response.Content.ReadAsStringAsync();
        Console.WriteLine(json);
    }
}

static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string url, T data)
    {
        var content = new StringContent(JsonSerializer.Serialize(data));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        return await client.PostAsync(url, content);
    }
}

Translation notes

  • All implementations use environment variables for secrets (GITHUB_TOKEN)
  • JSON bodies are sent as structured objects, not raw strings
  • Error handling checks HTTP status codes and prints errors if present
  • Headers are preserved exactly as in the cURL command
  • Libraries chosen are idiomatic for each language

Common pitfalls when porting

  • Forgetting to set GITHUB_TOKEN environment variable before running code
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Using raw strings for JSON bodies instead of structured objects
  • Hardcoding secrets in source code instead of using environment variables
  • Ignoring SSL/TLS verification in Go or other low-level clients

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 secret exposure in version control or logs. They also allow different deployments to use different credentials without code changes.

How do I install the required dependencies for each language?

Each language has its own package manager: Python (pip install requests httpx), Node.js (npm install axios node-fetch), Go (go get), PHP (composer), Ruby (gem install), Swift (Swift Package Manager), Rust (cargo add reqwest serde_json), C# (NuGet).

Why does the Swift example use RunLoop.main.run()?

Swift's URLSession is asynchronous. The example uses RunLoop.main.run() to keep the program running long enough to receive the response, which is necessary in a command-line context. In a real app, you'd typically use async/await or callbacks.