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/repos/octocat/Hello-World/releases -H "Authorization: token ghp_1234567890abcdef" -d '{"tag_name":"v1.0.0","name":"Release 1.0.0"}' -H "Accept: application/vnd.github.v3+json"

Python · requests

import os
import requests

url = "https://api.github.com/repos/octocat/Hello-World/releases"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "tag_name": "v1.0.0",
    "name": "Release 1.0.0"
}

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/repos/octocat/Hello-World/releases"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "tag_name": "v1.0.0",
    "name": "Release 1.0.0"
}

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 { env } from 'process';

const url = new URL('https://api.github.com/repos/octocat/Hello-World/releases');
const headers = {
  'Authorization': `token ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github.v3+json'
};
const body = JSON.stringify({
  tag_name: 'v1.0.0',
  name: 'Release 1.0.0'
});

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

Node.js · axios

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

const url = 'https://api.github.com/repos/octocat/Hello-World/releases';
const headers = {
  'Authorization': `token ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github.v3+json'
};
const data = {
  tag_name: 'v1.0.0',
  name: 'Release 1.0.0'
};

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

Go · net/http

package main

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

type Release struct {
	TagName string `json:"tag_name"`
	Name    string `json:"name"`
}

func main() {
	url := "https://api.github.com/repos/octocat/Hello-World/releases"
	token := os.Getenv("GITHUB_TOKEN")
	if token == "" {
		fmt.Println("GITHUB_TOKEN environment variable not set")
		os.Exit(1)
	}

	body := Release{
		TagName: "v1.0.0",
		Name:    "Release 1.0.0",
	}
	jsonBody, _ := json.Marshal(body)

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

	req.Header.Set("Authorization", "token "+token)
	req.Header.Set("Accept", "application/vnd.github.v3+json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		os.Exit(1)
	}
	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))
		os.Exit(1)
	}

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	fmt.Println(result)
}

PHP · cURL

<?php

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

$data = [
    'tag_name' => 'v1.0.0',
    'name' => 'Release 1.0.0'
];

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

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

if ($result === false) {
    die('Request failed');
}

$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/repos/octocat/Hello-World/releases')
token = ENV.fetch('GITHUB_TOKEN') { raise 'GITHUB_TOKEN environment variable not set' }

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

request = Net::HTTP::Post.new(url.path)
request['Authorization'] = "token #{token}"
request['Accept'] = 'application/vnd.github.v3+json'
request.body = { tag_name: 'v1.0.0', name: 'Release 1.0.0' }.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 JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.github.com/repos/octocat/Hello-World/releases")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? {
    fatalError("GITHUB_TOKEN environment variable not set")
}()

request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")

let body: [String: Any] = [
    "tag_name": "v1.0.0",
    "name": "Release 1.0.0"
]

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::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.github.com/repos/octocat/Hello-World/releases";
    let token = env::var("GITHUB_TOKEN")?;

    let client = Client::new();
    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        header::HeaderValue::from_str(&format!("token {}", token))?,
    );
    headers.insert(
        "Accept",
        header::HeaderValue::from_static("application/vnd.github.v3+json"),
    );

    let body: HashMap<&str, &str> = HashMap::from([
        ("tag_name", "v1.0.0"),
        ("name", "Release 1.0.0"),
    ]);

    let response = client
        .post(url)
        .headers(headers)
        .json(&body)
        .send()?;

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

    let json: serde_json::Value = response.json()?;
    println!("{}", json);

    Ok(())
}

C# · HttpClient

using System;
using System.Collections.Generic;
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/repos/octocat/Hello-World/releases";
        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("token", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

        var body = new Dictionary<string, string>
        {
            { "tag_name", "v1.0.0" },
            { "name", "Release 1.0.0" }
        };

        var response = await client.PostAsJsonAsync(url, body);
        response.EnsureSuccessStatusCode();

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

Translation notes

  • All implementations use environment variables for secrets (GITHUB_TOKEN)
  • JSON bodies are sent as objects/dicts, not raw strings
  • Error handling checks HTTP status and reads response body
  • Headers are preserved exactly as in the cURL command
  • Each language uses its idiomatic HTTP client library

Common pitfalls when porting

  • Forgetting to set GITHUB_TOKEN environment variable
  • Not handling HTTP errors (status codes >= 400)
  • Sending raw JSON strings instead of proper JSON objects
  • Ignoring SSL/TLS verification (especially in Go/Ruby)
  • Not setting Content-Type header for JSON bodies (PHP/Ruby)
  • Using deprecated HTTP clients in older language versions

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 prevent secrets from being committed to version control and allow different configurations across environments without code changes.

How do I handle pagination in the response?

GitHub API responses include pagination headers. Check 'Link' header for next/prev URLs and follow them iteratively.

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

It's needed to keep the program running while the async task completes, as URLSession tasks are asynchronous.

How do I add query parameters to the URL?

Construct the URL with query parameters using the language's URL builder (e.g., URLSearchParams in JavaScript, URI in Ruby).