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/owner/repo/issues/42/comments -H "Authorization: token ghp_abcdefghijklmnopqrstuvwxyz" -d '{"body":"This is a test comment"}'

Python · requests

import os
import requests

response = requests.post(
    url="https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments",
    headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"},
    json={"body": "This is a test comment"}
)
response.raise_for_status()

Python · httpx

import os
import httpx

response = httpx.post(
    url="https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments",
    headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"},
    json={"body": "This is a test comment"}
)
response.raise_for_status()

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch("https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments", {
  method: 'POST',
  headers: {
    'Authorization': `token ${process.env.GITHUB_TOKEN}`
  },
  body: JSON.stringify({"body": "This is a test comment"})
});

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();

Node.js · axios

import axios from 'axios';

const response = await axios.post(
  "https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments",
  {"body": "This is a test comment"},
  {
    headers: {
      'Authorization': `token ${process.env.GITHUB_TOKEN}`
    }
  }
);

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	req, err := http.NewRequest("POST", "https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments", nil)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "token "+os.Getenv("GITHUB_TOKEN"))
	req.Header.Set("Content-Type", "application/json")

	body := map[string]string{"body": "This is a test comment"}
	if err := req.ParseForm(); err != nil {
		panic(err)
	}
	// For JSON, we need to set the body separately
	req.Body = io.NopCloser(strings.NewReader(`{"body":"This is a test comment"}`))

	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("HTTP error! status: %s", resp.Status))
	}
}

PHP · cURL

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["body" => "This is a test comment"]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: token ' . getenv('GITHUB_TOKEN'),
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

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

curl_close($ch);

$body = json_decode($response, true);

Ruby · net/http

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

uri = URI.parse("https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "token #{ENV['GITHUB_TOKEN']}"
request['Content-Type'] = 'application/json'
request.body = { body: "This is a test comment" }.to_json

response = http.request(request)

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

Swift · URLSession

import Foundation

let url = URL(string: "https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("token \(ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: String] = ["body": "This is a test comment"]
request.httpBody = try JSONSerialization.data(withJSONObject: body)

let (data, response) = try await URLSession.shared.data(for: request)

if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
    throw URLError(.badServerResponse)
}

Rust · reqwest

use reqwest;
use std::env;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = reqwest::Client::new();
    let response = client
        .post("https://api.github.com/repos/${GITHUB_OWNER}/repo/issues/42/comments")
        .header("Authorization", format!("token {}", env::var("GITHUB_TOKEN").unwrap()))
        .json(&serde_json::json!({"body": "This is a test comment"}))
        .send()
        .await?;

    if !response.status().is_success() {
        panic!("HTTP error! status: {}", response.status());
    }

    let _body = response.json::<serde_json::Value>().await?;
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("https://api.github.com");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", Environment.GetEnvironmentVariable("GITHUB_TOKEN"));
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var content = new StringContent("{\"body\":\"This is a test comment\"}", System.Text.Encoding.UTF8, "application/json");
        var response = await client.PostAsync("/repos/${GITHUB_OWNER}/repo/issues/42/comments", content);

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

        var body = await response.Content.ReadAsStringAsync();
    }
}

Translation notes

  • All implementations use environment variables for secrets (GITHUB_TOKEN).
  • Python, Node.js, Ruby, Swift, Rust, and C# use idiomatic HTTP clients.
  • Go uses net/http for simplicity.
  • PHP uses cURL for consistency with the original command.
  • All JSON bodies are sent as objects, not raw strings.
  • Error handling checks HTTP status codes and raises exceptions where appropriate.

Common pitfalls when porting

  • Forgetting to set Content-Type header in Go or PHP may cause API to reject the request.
  • In Go, forgetting to set http.use_ssl = true will fail on HTTPS endpoints.
  • In Swift, ensure the environment variable is set in the scheme or launch arguments.
  • In Rust, the reqwest client must be async and awaited properly.
  • In C#, the HttpClient should ideally be reused (not recreated per request) for performance.

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

Environment variables prevent secrets from being committed to version control, reducing the risk of exposure.

How do I set the GITHUB_TOKEN environment variable?

In most shells: `export GITHUB_TOKEN=ghp_yourtokenhere` or in .env files for local development.

Why does the Go example use strings.NewReader for the body?

Go's net/http requires an io.Reader for the request body. strings.NewReader converts a string to an io.Reader.