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/git/refs \
  -H "Authorization: token ghp_1234567890" \
  -d '{"ref":"refs/heads/feature-branch","sha":"abc123def456"}'

Python · requests

import os
import requests

owner = os.environ["OWNER"]
repo = os.environ["REPO"]
token = os.environ["GITHUB_TOKEN"]

url = f"https://api.github.com/repos/{owner}/{repo}/git/refs"
headers = {"Authorization": f"Bearer {token}"}
data = {"ref": "refs/heads/feature-branch", "sha": "abc123def456"}

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

Python · httpx

import os
import httpx

owner = os.environ["OWNER"]
repo = os.environ["REPO"]
token = os.environ["GITHUB_TOKEN"]

url = f"https://api.github.com/repos/{owner}/{repo}/git/refs"
headers = {"Authorization": f"Bearer {token}"}
data = {"ref": "refs/heads/feature-branch", "sha": "abc123def456"}

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

Node.js · fetch

import { Buffer } from 'buffer';
import process from 'process';

const owner = process.env.OWNER;
const repo = process.env.REPO;
const token = process.env.GITHUB_TOKEN;

const url = `https://api.github.com/repos/${owner}/${repo}/git/refs`;
const headers = {
  'Authorization': `Bearer ${token}`
};
const body = JSON.stringify({
  ref: 'refs/heads/feature-branch',
  sha: 'abc123def456'
});

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

Node.js · axios

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

const owner = process.env.OWNER;
const repo = process.env.REPO;
const token = process.env.GITHUB_TOKEN;

const url = `https://api.github.com/repos/${owner}/${repo}/git/refs`;
const headers = {
  'Authorization': `Bearer ${token}`
};
const data = {
  ref: 'refs/heads/feature-branch',
  sha: 'abc123def456'
};

axios.post(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Error:', error.response.status, error.response.data);
    } else {
      console.error('Error:', error.message);
    }
  });

Go · net/http

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

type Ref struct {
	Ref string `json:"ref"`
	Sha string `json:"sha"`
}

func main() {
	owner := os.Getenv("OWNER")
	repo := os.Getenv("REPO")
	token := os.Getenv("GITHUB_TOKEN")

	url := fmt.Sprintf("https://api.github.com/repos/%s/%s/git/refs", owner, repo)
	data := Ref{
		Ref: "refs/heads/feature-branch",
		Sha: "abc123def456",
	}
	jsonData, _ := json.Marshal(data)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

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

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("Request failed with status: %s", resp.Status)
	}

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

PHP · cURL

<?php

$owner = getenv('OWNER');
$repo = getenv('REPO');
$token = getenv('GITHUB_TOKEN');

$url = "https://api.github.com/repos/{$owner}/{$repo}/git/refs";
$data = [
    'ref' => 'refs/heads/feature-branch',
    'sha' => 'abc123def456'
];

$options = [
    'http' => [
        'header' => "Authorization: Bearer {$token}\r\n",
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

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

if ($result === FALSE) {
    throw new Exception("Request failed");
}

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

Ruby · net/http

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

owner = ENV['OWNER']
repo = ENV['REPO']
token = ENV['GITHUB_TOKEN']

uri = URI.parse("https://api.github.com/repos/#{owner}/#{repo}/git/refs")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{token}"
request.body = { ref: 'refs/heads/feature-branch', sha: 'abc123def456' }.to_json
request['Content-Type'] = 'application/json'

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed: #{response.code} #{response.message}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let owner = ProcessInfo.processInfo.environment["OWNER"] ?? ""
let repo = ProcessInfo.processInfo.environment["REPO"] ?? ""
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""

let url = URL(string: "https://api.github.com/repos/" + owner + "/" + repo + "/git/refs")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "ref": "refs/heads/feature-branch",
    "sha": "abc123def456"
]
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")
        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 owner = env::var("OWNER")?;
    let repo = env::var("REPO")?;
    let token = env::var("GITHUB_TOKEN")?;

    let url = format!("https://api.github.com/repos/{}/{}/git/refs", owner, repo);
    let client = Client::new();
    let body = json!({
        "ref": "refs/heads/feature-branch",
        "sha": "abc123def456"
    });

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

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

    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.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        var owner = Environment.GetEnvironmentVariable("OWNER");
        var repo = Environment.GetEnvironmentVariable("REPO");
        var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");

        var url = $"https://api.github.com/repos/{owner}/{repo}/git/refs";
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, url);

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        request.Content = new StringContent(JsonSerializer.Serialize(new {
            @ref = "refs/heads/feature-branch",
            sha = "abc123def456"
        }));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed: {response.StatusCode}");
        }

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

Translation notes

  • All implementations use environment variables for secrets (OWNER, REPO, GITHUB_TOKEN)
  • Bearer token is used instead of 'token' prefix for modern API standards
  • JSON bodies are sent as objects/dicts, not raw strings
  • Error handling checks HTTP status and throws/raises on failure
  • Each language uses its idiomatic HTTP client library
  • URLs are constructed with placeholders for environment variables

Common pitfalls when porting

  • Forgetting to set Content-Type header for JSON requests
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Hardcoding secrets in source code instead of using environment variables
  • Using deprecated HTTP clients in older language versions
  • Not properly escaping URL components when constructing the path

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 Bearer token instead of 'token ghp_...'?

Modern APIs prefer the Bearer token scheme (RFC 6750) over the legacy 'token' prefix. GitHub's API accepts both, but Bearer is the standard.

Can I use a different environment variable name for the token?

Yes, but ensure consistency across all implementations. Common alternatives are GITHUB_API_TOKEN or GITHUB_AUTH_TOKEN.

What if the API requires a different authentication method?

Replace the Authorization header with the required scheme (e.g., Basic Auth, API key in headers, etc.) and adjust the token variable accordingly.

How do I handle rate limits in these examples?

Add logic to check response headers like 'X-RateLimit-Remaining' and implement retry/backoff strategies when needed.