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/pulls \
  -H "Authorization: token ghp_1234567890" \
  -H "Accept: application/vnd.github.v3+json" \
  -d '{"title":"Fix bug","head":"feature-branch","base":"main"}'

Python · requests

import os
import requests

response = requests.post(
    url="https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls",
    headers={
        "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
        "Accept": "application/vnd.github.v3+json"
    },
    json={"title": "Fix bug", "head": "feature-branch", "base": "main"}
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

with httpx.Client() as client:
    response = client.post(
        url="https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls",
        headers={
            "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
            "Accept": "application/vnd.github.v3+json"
        },
        json={"title": "Fix bug", "head": "feature-branch", "base": "main"}
    )
    response.raise_for_status()
    print(response.json())

Node.js · fetch

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

(async () => {
  const response = await fetch("https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls", {
    method: 'POST',
    headers: {
      'Authorization': `token ${process.env.GITHUB_TOKEN}`,
      'Accept': 'application/vnd.github.v3+json'
    },
    body: JSON.stringify({"title": "Fix bug", "head": "feature-branch", "base": "main"})
  });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  console.log(await response.json());
})();

Node.js · axios

import axios from 'axios';
import * as process from 'process';

(async () => {
  const response = await axios.post(
    "https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls",
    {"title": "Fix bug", "head": "feature-branch", "base": "main"},
    {
      headers: {
        'Authorization': `token ${process.env.GITHUB_TOKEN}`,
        'Accept': 'application/vnd.github.v3+json'
      }
    }
  );
  console.log(response.data);
})();

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	url := fmt.Sprintf("https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls")

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

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

	body := map[string]interface{}{
		"title": "Fix bug",
		"head":  "feature-branch",
		"base":  "main",
	}
	bodyBytes, _ := json.Marshal(body)
	req.Body = http.NoBody
	req.Body = http.NoBody
	req.GetBody = func() (io.ReadCloser, error) {
		return io.NopCloser(bytes.NewReader(bodyBytes)), nil
	}

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

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

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

PHP · cURL

<?php

$ch = curl_init();
$url = sprintf("https://api.github.com/repos/%s/%s/pulls", getenv('GITHUB_OWNER'), getenv('GITHUB_REPO'));

$payload = json_encode([
    'title' => 'Fix bug',
    'head' => 'feature-branch',
    'base' => 'main'
]);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: token ' . getenv('GITHUB_TOKEN'),
    'Accept: application/vnd.github.v3+json',
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Error:' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200 && $httpCode !== 201) {
    die("HTTP error! status: $httpCode");
}

$decoded = json_decode($response, true);
print_r($decoded);
curl_close($ch);

Ruby · net/http

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

uri = URI.parse("https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls")
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['Accept'] = 'application/vnd.github.v3+json'
request.body = {
  title: 'Fix bug',
  head: 'feature-branch',
  base: 'main'
}.to_json

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/pulls")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("token \(ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")

let body: [String: Any] = [
    "title": "Fix bug",
    "head": "feature-branch",
    "base": "main"
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    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 client = Client::new();
    let url = format!(
        "https://api.github.com/repos/{}/{}/pulls",
        env::var("GITHUB_OWNER")?,
        env::var("GITHUB_REPO")?
    );

    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        format!("token {}", env::var("GITHUB_TOKEN")?).parse()?,
    );
    headers.insert(
        "Accept",
        "application/vnd.github.v3+json".parse()?,
    );

    let body: HashMap<&str, &str> = HashMap::from([
        ("title", "Fix bug"),
        ("head", "feature-branch"),
        ("base", "main"),
    ]);

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

    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).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 client = new HttpClient();
        var url = $"https://api.github.com/repos/{Environment.GetEnvironmentVariable("GITHUB_OWNER")}/{Environment.GetEnvironmentVariable("GITHUB_REPO")}/pulls";

        var request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Headers.Authorization = new AuthenticationHeaderValue("token", Environment.GetEnvironmentVariable("GITHUB_TOKEN"));
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

        var body = new Dictionary<string, string>
        {
            { "title", "Fix bug" },
            { "head", "feature-branch" },
            { "base", "main" }
        };

        request.Content = new StringContent(JsonSerializer.Serialize(body));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

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

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

Translation notes

  • All implementations use environment variables for secrets (GITHUB_TOKEN, GITHUB_OWNER, GITHUB_REPO)
  • JSON bodies are sent as objects/dicts, not raw strings
  • Error handling checks HTTP status codes and raises/throws on failure
  • Headers are preserved exactly as in the cURL command
  • URL is constructed with placeholders for environment variables

Common pitfalls when porting

  • Forgetting to set GITHUB_TOKEN in the environment will cause auth failures
  • Using raw strings for JSON bodies instead of proper serialization can lead to encoding issues
  • Not checking HTTP status codes may hide API errors
  • Hardcoding secrets in code instead of using environment variables is a security risk
  • In Go, the request body handling requires special care to avoid issues with retries

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 are the idiomatic way to handle secrets in all languages. They prevent secrets from being committed to version control and allow for different configurations across environments.

How do I set the environment variables for this script?

For local development, set them in your shell (e.g., export GITHUB_TOKEN=your_token). In production, use your deployment platform's secret management (e.g., Kubernetes secrets, AWS Secrets Manager).

Why does the Go implementation look more complex?

Go's standard library requires explicit handling of request bodies for retries. The GetBody function ensures the body can be read multiple times if needed.