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/releases \
  --header "Authorization: token ghp_1234567890" \
  --header "Accept: application/vnd.github.v3+json" \
  --data '{"tag_name":"v1.0.0", "name":"Release v1.0.0", "body":"Initial release", "draft":false, "prerelease":false}'

Python · requests

import os
import requests

url = f"https://api.github.com/repos/{os.environ['GITHUB_OWNER']}/{os.environ['GITHUB_REPO']}/releases"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "tag_name": "v1.0.0",
    "name": "Release v1.0.0",
    "body": "Initial release",
    "draft": False,
    "prerelease": False
}

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

Python · httpx

import os
import httpx

url = f"https://api.github.com/repos/{os.environ['GITHUB_OWNER']}/{os.environ['GITHUB_REPO']}/releases"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "tag_name": "v1.0.0",
    "name": "Release v1.0.0",
    "body": "Initial release",
    "draft": False,
    "prerelease": False
}

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 * as process from 'process';

const url = `https://api.github.com/repos/${process.env.GITHUB_OWNER}/${process.env.GITHUB_REPO}/releases`;
const headers = {
  "Authorization": `token ${process.env.GITHUB_TOKEN}`,
  "Accept": "application/vnd.github.v3+json"
};
const data = {
  tag_name: "v1.0.0",
  name: "Release v1.0.0",
  body: "Initial release",
  draft: false,
  prerelease: false
};

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .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 * as process from 'process';

const url = `https://api.github.com/repos/${process.env.GITHUB_OWNER}/${process.env.GITHUB_REPO}/releases`;
const headers = {
  "Authorization": `token ${process.env.GITHUB_TOKEN}`,
  "Accept": "application/vnd.github.v3+json"
};
const data = {
  tag_name: "v1.0.0",
  name: "Release v1.0.0",
  body: "Initial release",
  draft: false,
  prerelease: false
};

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"`
	Draft      bool   `json:"draft"`
	Prerelease bool   `json:"prerelease"`
}

func main() {
	url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases",
		os.Getenv("GITHUB_OWNER"), os.Getenv("GITHUB_REPO"))

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

	body, _ := json.Marshal(release)

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

	req.Header.Set("Authorization", "token "+os.Getenv("GITHUB_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

$url = sprintf(
    'https://api.github.com/repos/%s/%s/releases',
    urlencode(getenv('GITHUB_OWNER')),
    urlencode(getenv('GITHUB_REPO'))
);

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

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

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

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 201) {
    die("Request failed with status: $httpCode");
}

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

Ruby · net/http

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

uri = URI.parse("https://api.github.com/repos/#{ENV['GITHUB_OWNER']}/#{ENV['GITHUB_REPO']}/releases")
headers = {
  "Authorization" => "token #{ENV['GITHUB_TOKEN']}",
  "Accept" => "application/vnd.github.v3+json"
}
data = {
  tag_name: "v1.0.0",
  name: "Release v1.0.0",
  body: "Initial release",
  draft: false,
  prerelease: false
}

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.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 owner = ProcessInfo.processInfo.environment["GITHUB_OWNER"] ?? ""
let repo = ProcessInfo.processInfo.environment["GITHUB_REPO"] ?? ""
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""

let url = URL(string: "https://api.github.com/repos/" + owner + "/" + repo + "/releases")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("token " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")

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

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()
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("GITHUB_OWNER")?;
    let repo = env::var("GITHUB_REPO")?;
    let token = env::var("GITHUB_TOKEN")?;

    let url = format!("https://api.github.com/repos/{}/{}/releases", owner, repo);
    let client = Client::new();

    let body = json!({
        "tag_name": "v1.0.0",
        "name": "Release v1.0.0",
        "body": "Initial release",
        "draft": false,
        "prerelease": false
    });

    let response = client
        .post(&url)
        .header("Authorization", format!("token {}", token))
        .header("Accept", "application/vnd.github.v3+json")
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed with 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.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main(string[] args)
    {
        var owner = Environment.GetEnvironmentVariable("GITHUB_OWNER");
        var repo = Environment.GetEnvironmentVariable("GITHUB_REPO");
        var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");

        var url = $"https://api.github.com/repos/{owner}/{repo}/releases";
        var client = new HttpClient();

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

        var request = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = new StringContent(JsonSerializer.Serialize(body))
            {
                Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
            }
        };

        request.Headers.Authorization = new AuthenticationHeaderValue("token", token);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed with status: {response.StatusCode}");
        }

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

Translation notes

  • Environment variables are used for secrets (GITHUB_OWNER, GITHUB_REPO, GITHUB_TOKEN)
  • All implementations preserve the original method, URL, headers, and body fidelity
  • Error handling includes status code checks and body reading where applicable
  • JSON bodies are constructed as objects/dicts, not raw strings
  • Bearer token is redacted in the parsed output

Common pitfalls when porting

  • Forgetting to set the Content-Type header to application/json in Go/PHP/Ruby
  • Not handling SSL/TLS properly in Go/Rust/Swift
  • Missing async/await in C# for HTTP calls
  • Not properly escaping environment variables in PHP
  • Assuming the API always returns 200 OK (GitHub may return 201 Created)
  • Not setting the Accept header to application/vnd.github.v3+json

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 instead of hardcoding?

Environment variables are the standard way to handle secrets in applications to avoid accidental exposure in version control or logs.

How do I handle pagination in GitHub API requests?

GitHub API responses include Link headers for pagination. Use the 'next' relation to fetch subsequent pages.

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 limiting in these examples?

Check the X-RateLimit-Remaining and X-RateLimit-Reset headers in the response. Implement exponential backoff if needed.