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" \
  -H "Accept: application/vnd.github.v3+json" \
  -d '{"title":"Bug report","body":"Issue description","labels":["bug"]}'

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}/issues"
headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "title": "Bug report",
    "body": "Issue description",
    "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['OWNER']
repo = os.environ['REPO']
token = os.environ['GITHUB_TOKEN']

url = f"https://api.github.com/repos/{owner}/{repo}/issues"
headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "title": "Bug report",
    "body": "Issue description",
    "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 { 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}/issues`;
const headers = {
  "Authorization": `Bearer ${token}`,
  "Accept": "application/vnd.github.v3+json"
};
const body = JSON.stringify({
  title: "Bug report",
  body: "Issue description",
  labels: ["bug"]
});

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

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}/issues`;
const headers = {
  "Authorization": `Bearer ${token}`,
  "Accept": "application/vnd.github.v3+json"
};
const data = {
  title: "Bug report",
  body: "Issue description",
  labels: ["bug"]
};

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 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:  "Bug report",
		Body:   "Issue description",
		Labels: []string{"bug"},
	}
	body, _ := json.Marshal(data)

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

	req.Header.Set("Authorization", "Bearer "+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("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}/issues";
$data = [
    'title' => 'Bug report',
    'body' => 'Issue description',
    'labels' => ['bug']
];

$options = [
    'http' => [
        'header' => [
            "Authorization: Bearer {$token}",
            "Accept: application/vnd.github.v3+json",
            "Content-Type: application/json"
        ],
        'method' => 'POST',
        'content' => json_encode($data)
    ]
];

$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}/issues")
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['Accept'] = 'application/vnd.github.v3+json'
request.body = {
  title: 'Bug report',
  body: 'Issue description',
  labels: ['bug']
}.to_json

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed with status #{response.code}"
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 + "/issues")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "title": "Bug report",
    "body": "Issue description",
    "labels": ["bug"]
]
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 == 201 else {
        print("Request failed with status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}
task.resume()

// Keep the program running to allow async task to complete
RunLoop.main.run()

Rust · reqwest

use reqwest;
use serde_json::json;
use std::env;

#[tokio::main]
async 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 = reqwest::Client::new();

    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", token))
        .header("Accept", "application/vnd.github.v3+json")
        .json(&json!({
            "title": "Bug report",
            "body": "Issue description",
            "labels": ["bug"]
        }))
        .send()
        .await?;

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

    let body = response.json::<serde_json::Value>().await?;
    println!("{}", body);

    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";
        using var client = new HttpClient();

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

        var body = new
        {
            title = "Bug report",
            body = "Issue description",
            labels = new[] { "bug" }
        };

        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($"Request failed with status: {response.StatusCode}");
        }

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

Translation notes

  • All implementations use environment variables for secrets (OWNER, REPO, GITHUB_TOKEN)
  • Bearer token is constructed dynamically from the environment variable
  • JSON body is sent as an object/struct/dict, not a raw string
  • Error handling checks HTTP status and throws/raises on failure
  • All libraries are idiomatic for their language (requests, httpx, fetch, axios, net/http, etc.)

Common pitfalls when porting

  • Forgetting to set Content-Type header for JSON bodies in some libraries
  • Not handling async/await properly in Swift or Rust
  • Missing SSL/TLS configuration in Go or Ruby (though defaults usually work)
  • Assuming the API returns JSON without checking Content-Type header
  • Hardcoding secrets in code instead of using environment variables

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' prefix?

GitHub API v3 accepts both 'token ghp_...' and 'Bearer ghp_...' in the Authorization header. Using 'Bearer' is more standard and works universally across APIs.

How do I set the environment variables?

For local testing, use `export OWNER=myuser REPO=myrepo GITHUB_TOKEN=ghp_...` in bash/zsh or `set OWNER=myuser REPO=myrepo GITHUB_TOKEN=ghp_...` in Windows cmd. In production, use your deployment platform's secret management.

Why does the Go example use bytes.NewBuffer?

Go's http.NewRequest requires an io.Reader for the body. bytes.NewBuffer converts the JSON byte slice to a reader.

How do I handle rate limits from GitHub API?

Check the 'X-RateLimit-Remaining' header in the response. Implement exponential backoff or queue requests when approaching limits.