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/octocat/Hello-World/issues -H "Authorization: token ghp_1234567890abcdef" -d '{"title":"New issue","body":"Please fix this."}' -H "Accept: application/vnd.github.v3+json"

Python · requests

import os
import requests

url = "https://api.github.com/repos/octocat/Hello-World/issues"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "title": "New issue",
    "body": "Please fix this."
}

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

Python · httpx

import os
import httpx

url = "https://api.github.com/repos/octocat/Hello-World/issues"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "title": "New issue",
    "body": "Please fix this."
}

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

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'process';

const url = 'https://api.github.com/repos/octocat/Hello-World/issues';
const headers = {
  'Authorization': `token ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github.v3+json'
};
const data = {
  title: 'New issue',
  body: 'Please fix this.'
};

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

Node.js · axios

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

const url = 'https://api.github.com/repos/octocat/Hello-World/issues';
const headers = {
  'Authorization': `token ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github.v3+json'
};
const data = {
  title: 'New issue',
  body: 'Please fix this.'
};

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

Go · net/http

package main

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

type Issue struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}

func main() {
	url := "https://api.github.com/repos/octocat/Hello-World/issues"
	token := os.Getenv("GITHUB_TOKEN")
	if token == "" {
		log.Fatal("GITHUB_TOKEN environment variable not set")
	}

	data := Issue{
		Title: "New issue",
		Body:  "Please fix this.",
	}
	body, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	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 >= 400 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Error: %d - %s", resp.StatusCode, string(body))
	}

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

PHP · cURL

<?php

$url = 'https://api.github.com/repos/octocat/Hello-World/issues';
$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
    die('GITHUB_TOKEN environment variable not set');
}

$data = [
    'title' => 'New issue',
    'body' => 'Please fix this.'
];

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

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

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

Ruby · net/http

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

url = URI.parse('https://api.github.com/repos/octocat/Hello-World/issues')
token = ENV.fetch('GITHUB_TOKEN') { raise 'GITHUB_TOKEN environment variable not set' }

data = {
  title: 'New issue',
  body: 'Please fix this.'
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url.request_uri)
request['Authorization'] = "token #{token}"
request['Accept'] = 'application/vnd.github.v3+json'
request.body = data.to_json

response = http.request(request)

if response.code.to_i >= 400
  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/octocat/Hello-World/issues")!
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? { fatalError("GITHUB_TOKEN environment variable not set") }()

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "title": "New issue",
    "body": "Please fix this."
]
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
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("Error: \(httpResponse.statusCode) - \(String(data: 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::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://api.github.com/repos/octocat/Hello-World/issues";
    let token = env::var("GITHUB_TOKEN")?;

    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        header::HeaderValue::from_str(&format!("token {}", token))?,
    );
    headers.insert(
        "Accept",
        header::HeaderValue::from_static("application/vnd.github.v3+json"),
    );

    let client = Client::new();
    let mut body = HashMap::new();
    body.insert("title", "New issue");
    body.insert("body", "Please fix this.");

    let response = client
        .post(url)
        .headers(headers)
        .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.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 url = "https://api.github.com/repos/octocat/Hello-World/issues";
        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("token", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

        var body = new Dictionary<string, string>
        {
            { "title", "New issue" },
            { "body", "Please fix this." }
        };

        var response = await client.PostAsJsonAsync(url, body);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
        }
        else
        {
            var result = await response.Content.ReadFromJsonAsync<Dictionary<string, object>>();
            Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
        }
    }
}

Translation notes

  • Bearer token is read from GITHUB_TOKEN environment variable
  • All libraries use idiomatic HTTP clients (requests, httpx, fetch, axios, net/http, etc.)
  • JSON bodies are sent as objects/dicts, not raw strings
  • Error handling checks status code and prints body on failure
  • Content-Type is set automatically by most libraries for JSON bodies

Common pitfalls when porting

  • Forgetting to set Accept header may return unexpected response formats
  • Not using HTTPS can expose the token in transit
  • Assuming all APIs return JSON without checking Content-Type
  • Ignoring rate limits or authentication errors
  • Hardcoding tokens in source 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 environment variables for tokens instead of hardcoding?

Environment variables prevent tokens from being committed to version control or exposed in logs. They also allow easy rotation without code changes.

How do I handle rate limits in these examples?

Check the 'X-RateLimit-Remaining' header and implement retry logic with exponential backoff when approaching limits.

Can I use these examples with GitHub Enterprise?

Yes, replace 'api.github.com' with your enterprise GitHub API endpoint in the URL.