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 --header "Authorization: token ghp_abcdefghijklmnopqrstuvwxyz" --data '{"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"Bearer {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"Bearer {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 'node:process';

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

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 url = 'https://api.github.com/repos/octocat/Hello-World/releases';
const headers = {
  'Authorization': `Bearer ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github+json'
};
const data = {
  tag_name: 'v1.0.0',
  name: 'Release v1.0.0',
  body: 'Initial release'
};

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 (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"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")
	}

	data := Release{
		TagName: "v1.0.0",
		Name:    "Release v1.0.0",
		Body:    "Initial release",
	}
	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", "Bearer "+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 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("HTTP error! status: %d, body: %s", resp.StatusCode, 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/releases';
$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
    die('GITHUB_TOKEN environment variable not set');
}

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

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

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

if ($response === false) {
    die('Request failed');
}

$http_response = $http_response_header;
$status_code = explode(' ', $http_response[0])[1];
if ($status_code !== '201') {
    die("HTTP error! status: $status_code");
}

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

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')

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

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

request = Net::HTTP::Post.new(url.path, {
  'Authorization' => "Bearer #{token}",
  'Accept' => 'application/vnd.github+json',
  'Content-Type' => 'application/json'
})
request.body = body

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error! 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"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["GITHUB_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)

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("HTTP error! status: \(httpResponse.statusCode)")
        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 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!("Bearer {}", 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!("HTTP error! status: {}", 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 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("Bearer", 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($"HTTP error! status: {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from the GITHUB_TOKEN environment variable.
  • JSON body is sent as a structured object, not a raw string.
  • Error handling checks HTTP status and reads the response body.
  • GitHub API requires 'Accept: application/vnd.github+json' header for JSON responses.

Common pitfalls when porting

  • Forgetting to set the 'Accept' header may result in non-JSON responses from GitHub.
  • Not reading the token from an environment variable risks leaking secrets.
  • Using raw strings for JSON bodies instead of structured objects can lead to malformed requests.
  • Ignoring HTTP status codes may cause silent failures in production code.
  • Not setting the 'Content-Type: application/json' header may cause the server to reject the request.

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's API now prefers the 'Bearer' scheme for OAuth tokens, though 'token' may still work. Using 'Bearer' is more standard and future-proof.

Can I use a different environment variable name?

Yes, but ensure consistency across your codebase. Common alternatives include 'GITHUB_API_TOKEN' or 'GH_TOKEN'.

Why is the 'Accept' header required?

GitHub's API uses content negotiation. The 'Accept' header ensures you receive JSON responses, which is the expected format for most clients.