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_abc123def456ghi789jkl012mno345pqr678" \
  -d '{"ref":"refs/heads/feature-branch","sha":"1234567890abcdef1234567890abcdef12345678"}'

Python · requests

import os
import requests

url = "https://api.github.com/repos/owner/repo/git/refs"
headers = {
    "Authorization": f"Bearer {os.environ.get('GITHUB_TOKEN')}"
}
data = {
    "ref": "refs/heads/feature-branch",
    "sha": "1234567890abcdef1234567890abcdef12345678"
}

response = requests.post(url, headers=headers, json=data)
if response.status_code != 201:
    print(f"Error: {response.status_code} - {response.text}")
else:
    print(response.json())

Python · httpx

import os
import httpx

url = "https://api.github.com/repos/owner/repo/git/refs"
headers = {
    "Authorization": f"Bearer {os.environ.get('GITHUB_TOKEN')}"
}
data = {
    "ref": "refs/heads/feature-branch",
    "sha": "1234567890abcdef1234567890abcdef12345678"
}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    if response.status_code != 201:
        print(f"Error: {response.status_code} - {response.text}")
    else:
        print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { config } from 'dotenv';

config();

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

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

Node.js · axios

import axios from 'axios';
import { config } from 'dotenv';

config();

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

axios.post(url, data, { headers })
  .then(response => {
    if (response.status !== 201) {
      throw new Error(`Error: ${response.status} - ${response.statusText}`);
    }
    console.log(response.data);
  })
  .catch(error => {
    console.error(error.message);
  });

Go · net/http

package main

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

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

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

	data := Ref{
		Ref: "refs/heads/feature-branch",
		Sha: "1234567890abcdef1234567890abcdef12345678",
	}
	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("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.StatusCreated {
		body, _ := io.ReadAll(resp.Body)
		fmt.Printf("Error: %d - %s\n", resp.StatusCode, string(body))
		return
	}

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

PHP · cURL

<?php

$url = 'https://api.github.com/repos/owner/repo/git/refs';
$token = getenv('GITHUB_TOKEN');

if (empty($token)) {
    die('GITHUB_TOKEN environment variable not set');
}

$data = [
    'ref' => 'refs/heads/feature-branch',
    'sha' => '1234567890abcdef1234567890abcdef12345678'
];

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

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

if ($http_response_header[0] !== 'HTTP/1.1 201 Created') {
    echo "Error: " . $http_response_header[0] . " - " . $response . "\n";
} else {
    echo $response;
}

Ruby · net/http

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

url = URI.parse('https://api.github.com/repos/owner/repo/git/refs')
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, {
  'Authorization' => "Bearer #{token}",
  'Content-Type' => 'application/json'
})

request.body = {
  ref: 'refs/heads/feature-branch',
  sha: '1234567890abcdef1234567890abcdef12345678'
}.to_json

response = http.request(request)

if response.code != '201'
  puts "Error: #{response.code} - #{response.body}"
else
  puts JSON.parse(response.body)
end

Swift · URLSession

import Foundation

let url = URL(string: "https://api.github.com/repos/owner/repo/git/refs")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

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

request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "ref": "refs/heads/feature-branch",
    "sha": "1234567890abcdef1234567890abcdef12345678"
]

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 else {
        print("Invalid response")
        return
    }

    if httpResponse.statusCode != 201 {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print("Error: \(httpResponse.statusCode) - \(responseBody)")
        }
        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/repos/owner/repo/git/refs";
    let token = env::var("GITHUB_TOKEN")?;

    let client = Client::new();
    let body = json!({
        "ref": "refs/heads/feature-branch",
        "sha": "1234567890abcdef1234567890abcdef12345678"
    });

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

    if !response.status().is_success() {
        eprintln!("Error: {} - {}", response.status(), response.text()?);
    } else {
        println!("{:?}", response.json::<serde_json::Value>()?);
    }

    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/repos/owner/repo/git/refs";
        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);

        var body = new
        {
            @ref = "refs/heads/feature-branch",
            sha = "1234567890abcdef1234567890abcdef12345678"
        };

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

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
        }
        else
        {
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

public 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 the idiomatic HTTP client for each language.
  • Bearer token is read from environment variable GITHUB_TOKEN to avoid hardcoding secrets.
  • Error handling checks status code and prints error message if request fails.
  • JSON bodies are constructed as objects/dictionaries, not raw strings.
  • Go and Rust use blocking clients for simplicity; async versions would be more idiomatic in production.
  • PHP uses file_get_contents with stream context for simplicity.
  • Swift uses URLSession with a synchronous run loop for simplicity in a console app.

Common pitfalls when porting

  • Forgetting to set GITHUB_TOKEN environment variable will cause runtime errors.
  • Not setting Content-Type header to application/json may cause API to reject the request.
  • Ignoring SSL certificate validation (not shown here) can be a security risk in production.
  • In Go, the blocking client may not be suitable for high-concurrency applications.
  • In Swift, the synchronous run loop is not suitable for production iOS/macOS apps.

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 secret leakage in version control or logs. They also allow different configurations across environments (dev, staging, prod).

Can I use async/await in Go or Rust for better performance?

Yes, in Go you can use the standard library's http package with goroutines, and in Rust you can use reqwest's async client with tokio. The examples use blocking clients for simplicity.

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or pagination helpers. For example, in Python requests you can use response.iter_content(), and in Go you can use io.ReadAll() on the response body.