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/releases \
  -H "Authorization: token ghp_abcdefghijklmnopqrstuvwxyz1234567890" \
  -d '{"tag_name": "v1.0.0", "name": "Release v1.0.0", "body": "Initial release"}'

Python · requests

import os
import requests

url = "https://api.github.com/repos/octocat/Hello-World/releases"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github+json"
}
data = {
    "tag_name": "v1.0.0",
    "name": "Release v1.0.0",
    "body": "Initial release"
}

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

Python · httpx

import os
import httpx

url = "https://api.github.com/repos/octocat/Hello-World/releases"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github+json"
}
data = {
    "tag_name": "v1.0.0",
    "name": "Release v1.0.0",
    "body": "Initial release"
}

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

const url = new URL('https://api.github.com/repos/octocat/Hello-World/releases');
const headers = {
  'Authorization': `token ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github+json'
};
const body = JSON.stringify({
  tag_name: 'v1.0.0',
  name: 'Release v1.0.0',
  body: 'Initial release'
});

fetch(url, {
  method: 'POST',
  headers,
  body
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    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/releases';
const headers = {
  'Authorization': `token ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github+json'
};
const data = {
  tag_name: 'v1.0.0',
  name: 'Release v1.0.0',
  body: 'Initial release'
};

axios.post(url, data, { headers })
  .then(res => {
    console.log(res.data);
  })
  .catch(err => {
    console.error(err.message);
  });

Go · net/http

package main

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

type Release struct {
	TagName string `json:"tag_name"`
	Name    string `json:"name"`
	Body    string `json:"body"`
}

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

	release := Release{
		TagName: "v1.0.0",
		Name:    "Release v1.0.0",
		Body:    "Initial release",
	}

	body, err := json.Marshal(release)
	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+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{}
	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/releases';
$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
    die('GITHUB_TOKEN environment variable not set');
}

$headers = [
    'Authorization: token ' . $token,
    'Accept: application/vnd.github+json',
    'Content-Type: application/json'
];

$data = [
    'tag_name' => 'v1.0.0',
    'name' => 'Release v1.0.0',
    'body' => 'Initial release'
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die(curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 201) {
    die("Request failed with status: " . $httpCode);
}

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

Ruby · net/http

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

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

headers = {
  'Authorization' => "token #{token}",
  'Accept' => 'application/vnd.github+json'
}

data = {
  tag_name: 'v1.0.0',
  name: 'Release v1.0.0',
  body: 'Initial release'
}

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

request = Net::HTTP::Post.new(url.request_uri, headers)
request.body = data.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 url = URL(string: "https://api.github.com/repos/octocat/Hello-World/releases")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? { fatalError("GITHUB_TOKEN environment variable not set") }()
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")

let body: [String: Any] = [
    "tag_name": "v1.0.0",
    "name": "Release v1.0.0",
    "body": "Initial release"
]

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 {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    guard (200...299).contains(httpResponse.statusCode) else {
        print("Request failed with status: \(httpResponse.statusCode)")
        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::blocking::Client;
use serde_json::json;
use std::env;

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

    let client = Client::new();
    let response = client
        .post(url)
        .header("Authorization", format!("token {}", token))
        .header("Accept", "application/vnd.github+json")
        .json(&json!({
            "tag_name": "v1.0.0",
            "name": "Release v1.0.0",
            "body": "Initial release"
        }))
        .send()?;

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

    let body = response.json::<serde_json::Value>()?;
    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 url = "https://api.github.com/repos/octocat/Hello-World/releases";
        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+json"));

        var data = new
        {
            tag_name = "v1.0.0",
            name = "Release v1.0.0",
            body = "Initial release"
        };

        var response = await client.PostAsJsonAsync(url, data);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Request failed with status: {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use the official/supported HTTP client for the language.
  • Bearer token is read from environment variable GITHUB_TOKEN to avoid hardcoding.
  • JSON body is sent as an object/dict, not a raw string.
  • Error handling checks HTTP status and reads response body.
  • Accept header is set to GitHub API's recommended value.
  • Python implementations use both requests and httpx for completeness.

Common pitfalls when porting

  • Forgetting to set the Accept header may result in GitHub API returning HTML instead of JSON.
  • Not reading the token from environment variables risks exposing secrets in version control.
  • In Go, forgetting to set Content-Type header may cause the server to reject the request.
  • In Swift, the async task requires the main run loop to complete; production code should handle this differently.
  • In Rust, using blocking client for simplicity; async version would be more idiomatic in async contexts.

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 is the Accept header set to 'application/vnd.github+json'?

GitHub's API recommends this header to ensure responses are in the expected JSON format. Omitting it may result in HTML responses or version mismatches.

Can I use a different environment variable name for the token?

Yes, but ensure consistency across all implementations. The examples use GITHUB_TOKEN for clarity.

Why does the Go implementation use a struct for the request body?

Using a struct ensures type safety and proper JSON serialization. It's idiomatic in Go to define types for API interactions.