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 \
  -H "Authorization: token ghp_1234567890" \
  -d '{"title":"Bug report","body":"Issue description"}'

Python · requests

import os
import requests

response = requests.post(
    url="https://api.github.com/repos/${OWNER}/${REPO}/issues",
    headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"},
    json={"title": "Bug report", "body": "Issue description"}
)

if response.status_code >= 400:
    print(response.text)
else:
    print(response.json())

Python · httpx

import os
import httpx

response = httpx.post(
    url="https://api.github.com/repos/${OWNER}/${REPO}/issues",
    headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"},
    json={"title": "Bug report", "body": "Issue description"}
)

if response.status_code >= 400:
    print(response.text)
else:
    print(response.json())

Node.js · fetch

const fetch = require('node-fetch');

(async () => {
  const response = await fetch(
    `https://api.github.com/repos/${process.env.OWNER}/${process.env.REPO}/issues`,
    {
      method: 'POST',
      headers: {
        'Authorization': `token ${process.env.GITHUB_TOKEN}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: 'Bug report',
        body: 'Issue description'
      })
    }
  );

  if (!response.ok) {
    console.error(await response.text());
  } else {
    console.log(await response.json());
  }
})();

Node.js · axios

const axios = require('axios');

(async () => {
  try {
    const response = await axios.post(
      `https://api.github.com/repos/${process.env.OWNER}/${process.env.REPO}/issues`,
      {
        title: 'Bug report',
        body: 'Issue description'
      },
      {
        headers: {
          'Authorization': `token ${process.env.GITHUB_TOKEN}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(response.data);
  } catch (error) {
    if (error.response) {
      console.error(error.response.data);
    } else {
      console.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"`
}

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)
	body := Issue{Title: "Bug report", Body: "Issue description"}

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

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

	req.Header.Set("Authorization", fmt.Sprintf("token %s", 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 >= 400 {
		log.Fatal(resp.Status)
	}

	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' => 'Bug report',
    'body' => 'Issue description'
];

$options = [
    'http' => [
        'header' => "Authorization: token {$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 $response;
} else {
    echo $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}/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['Content-Type'] = 'application/json'
request.body = { title: 'Bug report', body: 'Issue description' }.to_json

response = http.request(request)

if response.code.to_i >= 400
  puts response.body
else
  puts JSON.parse(response.body)
end

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 + "/issues")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("token " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "title": "Bug report",
    "body": "Issue description"
]

request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print(error)
        return
    }

    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 else {
        print(String(data: data!, encoding: .utf8)!)
        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/{}/{}/issues", owner, repo);
    let client = Client::new();
    let response = client
        .post(&url)
        .header("Authorization", format!("token {}", token))
        .json(&json!({"title": "Bug report", "body": "Issue description"}))
        .send()?;

    if !response.status().is_success() {
        eprintln!("{}", 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.Threading.Tasks;
using Newtonsoft.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}/issues";
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", token);

        var body = new { title = "Bug report", body = "Issue description" };
        var response = await client.PostAsJsonAsync(url, body);

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        else
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
    }
}

Translation notes

  • All implementations use environment variables for sensitive data (OWNER, REPO, GITHUB_TOKEN).
  • Python, Node.js, Go, Ruby, Swift, Rust, and C# use idiomatic HTTP clients.
  • PHP uses file_get_contents with stream context for simplicity.
  • Error handling checks status code >= 400 and prints the response body.
  • JSON bodies are constructed as objects/dicts, not raw strings.
  • Headers are set explicitly for Content-Type and Authorization.

Common pitfalls when porting

  • Forgetting to set environment variables before running the code.
  • Not handling HTTP errors properly (e.g., ignoring status codes).
  • Using raw strings for JSON bodies instead of proper serialization.
  • Hardcoding sensitive data like tokens in the code.
  • Ignoring SSL/TLS verification in Go or other languages (not shown here but important in production).

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?

Environment variables are a secure way to handle sensitive data like API tokens. They avoid hardcoding secrets in source code and can be managed separately from the application.

How do I handle pagination in GitHub API responses?

GitHub API responses include a 'Link' header with pagination URLs. Use a library like requests in Python or axios in Node.js to follow these links automatically.

Why does the Go example use bytes.Buffer for the request body?

In Go, http.NewRequest requires an io.Reader for the body. bytes.Buffer is a convenient way to create an in-memory reader for JSON data.

How do I set custom timeouts for HTTP requests?

Most HTTP libraries allow setting timeouts. For example, in Python requests: requests.post(..., timeout=10). In Go: http.Client{Timeout: 10 * time.Second}.