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 \
  --header "Authorization: token ghp_1234567890" \
  --header "Accept: application/vnd.github.v3+json" \
  --data '{"title":"Fix bug", "body":"Please fix this bug", "labels":["bug"]}'

Python · requests

import os
import requests

owner = os.environ.get("OWNER")
repo = os.environ.get("REPO")
token = os.environ.get("GITHUB_TOKEN")

url = f"https://api.github.com/repos/{owner}/{repo}/issues"
headers = {
    "Authorization": f"token {token}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "title": "Fix bug",
    "body": "Please fix this bug",
    "labels": ["bug"]
}

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

Python · httpx

import os
import httpx

owner = os.environ.get("OWNER")
repo = os.environ.get("REPO")
token = os.environ.get("GITHUB_TOKEN")

url = f"https://api.github.com/repos/{owner}/{repo}/issues"
headers = {
    "Authorization": f"token {token}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "title": "Fix bug",
    "body": "Please fix this bug",
    "labels": ["bug"]
}

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 'node:process';

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

const url = `https://api.github.com/repos/${owner}/${repo}/issues`;
const headers = {
  "Authorization": `token ${token}`,
  "Accept": "application/vnd.github.v3+json"
};
const data = {
  title: "Fix bug",
  body: "Please fix this bug",
  labels: ["bug"]
};

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

Node.js · axios

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

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

const url = `https://api.github.com/repos/${owner}/${repo}/issues`;
const headers = {
  "Authorization": `token ${token}`,
  "Accept": "application/vnd.github.v3+json"
};
const data = {
  title: "Fix bug",
  body: "Please fix this bug",
  labels: ["bug"]
};

try {
  const response = await axios.post(url, data, { headers });
  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 Issue struct {
	Title  string   `json:"title"`
	Body   string   `json:"body"`
	Labels []string `json:"labels"`
}

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/issues", owner, repo)
	data := Issue{
		Title:  "Fix bug",
		Body:   "Please fix this bug",
		Labels: []string{"bug"},
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

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

	req.Header.Set("Authorization", "token "+token)
	req.Header.Set("Accept", "application/vnd.github.v3+json")
	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("unexpected status code: %d", resp.StatusCode)
	}

	var result map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	fmt.Println(result)
}

PHP · cURL

<?php

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

$url = "https://api.github.com/repos/{$owner}/{$repo}/issues";
$data = [
    'title' => 'Fix bug',
    'body' => 'Please fix this bug',
    'labels' => ['bug']
];

$options = [
    'http' => [
        'method' => 'POST',
        'header' => [
            "Authorization: token {$token}",
            "Accept: application/vnd.github.v3+json",
            "Content-Type: application/json"
        ],
        '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') {
    throw new Exception("Request failed: " . $http_response_header[0]);
}

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

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}/issues")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "token #{token}"
request['Accept'] = 'application/vnd.github.v3+json'
request.body = {
  title: 'Fix bug',
  body: 'Please fix this bug',
  labels: ['bug']
}.to_json

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

guard let owner = ProcessInfo.processInfo.environment["OWNER"],
      let repo = ProcessInfo.processInfo.environment["REPO"],
      let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] else {
    fatalError("Missing environment variables OWNER, REPO, or GITHUB_TOKEN")
}

let url = URL(string: "https://api.github.com/repos/" + owner + "/" + repo + "/issues")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("token " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")

let body: [String: Any] = [
    "title": "Fix bug",
    "body": "Please fix this bug",
    "labels": ["bug"]
]

request.httpBody = try JSONSerialization.data(withJSONObject: body)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

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: \((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 reqwest::blocking::Client;
use serde_json::json;
use std::env;

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/{}/{}/issues", owner, repo);
    let client = Client::new();
    let response = client
        .post(&url)
        .header("Authorization", format!("token {}", token))
        .header("Accept", "application/vnd.github.v3+json")
        .json(&json!({
            "title": "Fix bug",
            "body": "Please fix this bug",
            "labels": ["bug"]
        }))
        .send()?;

    if !response.status().is_success() {
        return Err(format!("HTTP error: {}", 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.Text.Json;
using System.Threading.Tasks;

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}/issues";
        var data = new
        {
            title = "Fix bug",
            body = "Please fix this bug",
            labels = new[] { "bug" }
        };

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

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

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

static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PostAsJsonAsync<T>(
        this HttpClient httpClient, string url, T data)
    {
        var content = new StringContent(JsonSerializer.Serialize(data));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        return await httpClient.PostAsync(url, content);
    }
}

Translation notes

  • All implementations use environment variables for secrets (OWNER, REPO, GITHUB_TOKEN).
  • Python, Node.js, Go, Ruby, Swift, Rust, and C# use idiomatic HTTP clients.
  • PHP uses stream context for simplicity (no external dependencies).
  • JSON bodies are sent as objects/dicts, not raw strings.
  • Error handling checks HTTP status codes and raises exceptions where appropriate.
  • Headers are preserved exactly as in the cURL command.

Common pitfalls when porting

  • Forgetting to set environment variables before running the code.
  • Not handling HTTP errors (e.g., rate limits, 404s) beyond basic status checks.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task runs asynchronously; ensure the RunLoop is active.
  • In Rust, the blocking client is used for simplicity; async is preferred in production.
  • In PHP, file_get_contents may not be suitable for large responses or complex workflows.

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 secrets?

Environment variables separate configuration from code, reducing the risk of accidental exposure (e.g., in version control).

How do I handle pagination or rate limits in these examples?

Extend the examples with retry logic (e.g., exponential backoff) and check the 'X-RateLimit-Remaining' header. Libraries like Axios or requests can be configured with interceptors.

Can I use a different HTTP client library?

Yes, but ensure it supports the same features (e.g., JSON serialization, headers, timeouts). For example, in Python, you could use httpx.AsyncClient for async requests.