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

Python · requests

import os
import requests

response = requests.post(
    url="https://api.github.com/repos/${OWNER}/${REPO}/releases",
    headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"},
    json={
        "tag_name": "v1.0.0",
        "name": "Release v1.0.0",
        "body": "Initial release.",
        "draft": False,
        "prerelease": False
    }
)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

response = httpx.post(
    url="https://api.github.com/repos/${OWNER}/${REPO}/releases",
    headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"},
    json={
        "tag_name": "v1.0.0",
        "name": "Release v1.0.0",
        "body": "Initial release.",
        "draft": False,
        "prerelease": False
    }
)
response.raise_for_status()
print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import process from 'process';

(async () => {
  const response = await fetch("https://api.github.com/repos/${OWNER}/${REPO}/releases", {
    method: 'POST',
    headers: {
      'Authorization': `token ${process.env.GITHUB_TOKEN}`
    },
    body: JSON.stringify({
      "tag_name": "v1.0.0",
      "name": "Release v1.0.0",
      "body": "Initial release.",
      "draft": false,
      "prerelease": false
    })
  });
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  const data = await response.json();
  console.log(data);
})();

Node.js · axios

import axios from 'axios';
import process from 'process';

(async () => {
  const response = await axios.post(
    "https://api.github.com/repos/${OWNER}/${REPO}/releases",
    {
      "tag_name": "v1.0.0",
      "name": "Release v1.0.0",
      "body": "Initial release.",
      "draft": false,
      "prerelease": false
    },
    {
      headers: {
        'Authorization': `token ${process.env.GITHUB_TOKEN}`
      }
    }
  );
  console.log(response.data);
})();

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() {
	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.",
		Draft:      false,
		Prerelease: false,
	}

	body, err := json.Marshal(release)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest(
		"POST",
		"https://api.github.com/repos/${OWNER}/${REPO}/releases",
		bytes.NewBuffer(body),
	)
	if err != nil {
		log.Fatal(err)
	}

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

$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
    die('GITHUB_TOKEN environment variable not set');
}

$url = 'https://api.github.com/repos/${OWNER}/${REPO}/releases';
$data = [
    'tag_name' => 'v1.0.0',
    'name' => 'Release v1.0.0',
    'body' => 'Initial release.',
    'draft' => false,
    'prerelease' => false
];

$options = [
    'http' => [
        'header' => "Authorization: token $token\r\n",
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

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

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

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

Ruby · net/http

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

token = ENV.fetch('GITHUB_TOKEN')
uri = URI.parse("https://api.github.com/repos/${OWNER}/${REPO}/releases")

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

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "token #{token}"
request.body = {
  tag_name: 'v1.0.0',
  name: 'Release v1.0.0',
  body: 'Initial release.',
  draft: false,
  prerelease: false
}.to_json

response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP request failed: #{response.code} #{response.message}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

guard let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] else {
    fatalError("GITHUB_TOKEN environment variable not set")
}

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/json", forHTTPHeaderField: "Content-Type")

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 {
        fatalError("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        fatalError("Request failed with status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    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 token = env::var("GITHUB_TOKEN")?;
    let client = Client::new();
    let response = client
        .post("https://api.github.com/repos/${OWNER}/${REPO}/releases")
        .header("Authorization", format!("token {}", token))
        .json(&json!({
            "tag_name": "v1.0.0",
            "name": "Release v1.0.0",
            "body": "Initial release.",
            "draft": false,
            "prerelease": false
        }))
        .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.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        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.BaseAddress = new Uri("https://api.github.com/");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", token);

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

        var response = await client.PostAsJsonAsync(
            $"repos/${Environment.GetEnvironmentVariable("OWNER")}/{Environment.GetEnvironmentVariable("REPO")}/releases",
            release
        );

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Request failed with status: {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use environment variables for secrets (GITHUB_TOKEN).
  • Python, Node.js, Go, Ruby, Rust, and C# use idiomatic HTTP clients with JSON serialization.
  • PHP uses file_get_contents with stream context for simplicity.
  • Swift uses URLSession with async/await pattern.
  • Error handling checks HTTP status codes and raises exceptions where appropriate.
  • URLs use placeholders for ${OWNER} and ${REPO} which should be replaced with actual values or environment variables.

Common pitfalls when porting

  • Forgetting to set GITHUB_TOKEN environment variable before running the code.
  • Not handling HTTP errors properly (e.g., ignoring status codes).
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the RunLoop.main.run() is necessary for async tasks to complete in a command-line context.
  • In PHP, the 'ignore_errors' option is used to avoid throwing warnings for non-200 responses, but errors should still be checked.
  • In Rust, the blocking client is used for simplicity; async would require a runtime like tokio.

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 prevent secrets from being committed to version control or exposed in logs. They also allow different configurations across environments (dev, staging, prod).

Can I use async/await in Python instead of requests?

Yes, you can use httpx.AsyncClient in Python for async operations, but the example uses the simpler synchronous requests library for clarity.

How do I set the environment variables before running the code?

For local development, set them in your shell: `export GITHUB_TOKEN=your_token_here` (Linux/macOS) or `set GITHUB_TOKEN=your_token_here` (Windows). In production, use your deployment platform's secret management (e.g., Kubernetes secrets, AWS Secrets Manager).

Why does the Swift example use RunLoop.main.run()?

In a command-line Swift application, the RunLoop is needed to keep the program running long enough for the async URLSession task to complete. In an iOS/macOS app, this isn't necessary.