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_abcdefghijklmnopqrstuvwxyz" --data '{"tag_name":"v1.0.0","name":"Release v1.0.0","body":"Initial release"}'

Python · requests

import os
import requests

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

Python · httpx

import os
import httpx

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

Node.js · fetch

import fetch from 'node-fetch';
import { config } from 'dotenv';

config();

const response = await fetch("https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/releases", {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    tag_name: "v1.0.0",
    name: "Release v1.0.0",
    body: "Initial release"
  })
});

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

Node.js · axios

import axios from 'axios';
import { config } from 'dotenv';

config();

const response = await axios.post(
  "https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/releases",
  {
    tag_name: "v1.0.0",
    name: "Release v1.0.0",
    body: "Initial release"
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
      'Content-Type': 'application/json'
    }
  }
);

if (response.status >= 400) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

Go · net/http

package main

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

func main() {
	token := os.Getenv("GITHUB_TOKEN")
	owner := os.Getenv("GITHUB_OWNER")
	repo := os.Getenv("GITHUB_REPO")

	body := map[string]string{
		"tag_name": "v1.0.0",
		"name":      "Release v1.0.0",
		"body":      "Initial release",
	}
	jsonBody, _ := json.Marshal(body)

	req, err := http.NewRequest(
		"POST",
		fmt.Sprintf("https://api.github.com/repos/%s/%s/releases", owner, repo),
		bytes.NewBuffer(jsonBody),
	)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("HTTP error! status: %d, body: %s", resp.StatusCode, body))
	}
}

PHP · cURL

<?php

$token = getenv('GITHUB_TOKEN');
$owner = getenv('GITHUB_OWNER');
$repo = getenv('GITHUB_REPO');

$url = "https://api.github.com/repos/{$owner}/{$repo}/releases";
$data = [
    'tag_name' => 'v1.0.0',
    'name' => 'Release v1.0.0',
    'body' => 'Initial release'
];

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

$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') {
    throw new Exception("HTTP error! status: " . $http_response_header[0]);
}

var_dump($response);

Ruby · net/http

require 'net/http'
require 'json'
require 'dotenv/load'

token = ENV['GITHUB_TOKEN']
owner = ENV['GITHUB_OWNER']
repo = ENV['GITHUB_REPO']

uri = URI("https://api.github.com/repos/#{owner}/#{repo}/releases")
req = Net::HTTP::Post.new(uri)
req['Authorization'] = "Bearer #{token}"
req['Content-Type'] = 'application/json'
req.body = {
  tag_name: 'v1.0.0',
  name: 'Release v1.0.0',
  body: 'Initial release'
}.to_json

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end

unless res.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{res.code}"
end

Swift · URLSession

import Foundation

let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""
let owner = ProcessInfo.processInfo.environment["GITHUB_OWNER"] ?? ""
let repo = ProcessInfo.processInfo.environment["GITHUB_REPO"] ?? ""

let url = URL(string: "https://api.github.com/repos/\\(owner)/\\(repo)/releases")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: String] = [
    "tag_name": "v1.0.0",
    "name": "Release v1.0.0",
    "body": "Initial release"
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)

let (data, response) = try await URLSession.shared.data(for: request)

if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
    throw URLError(.badServerResponse)
}

Rust · reqwest

use reqwest;
use serde_json::json;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = env::var("GITHUB_TOKEN")?;
    let owner = env::var("GITHUB_OWNER")?;
    let repo = env::var("GITHUB_REPO")?;

    let client = reqwest::Client::new();
    let response = client
        .post(format!("https://api.github.com/repos/{}/{}/releases", owner, repo))
        .header("Authorization", format!("Bearer {}", token))
        .json(&json!({
            "tag_name": "v1.0.0",
            "name": "Release v1.0.0",
            "body": "Initial release"
        }))
        .send()
        .await?;

    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).into());
    }

    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");
        var owner = Environment.GetEnvironmentVariable("GITHUB_OWNER");
        var repo = Environment.GetEnvironmentVariable("GITHUB_REPO");

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

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

        var response = await client.PostAsJsonAsync(
            $"https://api.github.com/repos/{owner}/{repo}/releases",
            body
        );

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }
    }
}

Translation notes

  • Bearer token is read from environment variable GITHUB_TOKEN
  • Owner and repo are read from environment variables GITHUB_OWNER and GITHUB_REPO
  • All implementations use idiomatic HTTP clients for their respective languages
  • JSON body is constructed as a dictionary/object literal
  • Error handling checks HTTP status code and raises/throws on failure

Common pitfalls when porting

  • Forgetting to set Content-Type header to application/json in raw HTTP clients
  • Not handling environment variable presence checks (may cause runtime errors)
  • Using string concatenation for URLs without proper escaping (security risk)
  • Ignoring SSL/TLS verification in low-level clients (not shown here as high-level clients handle it)
  • Assuming the API always returns 201 Created (may vary by endpoint)

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 API v3 requires the Authorization header to use 'Bearer' for OAuth tokens, though 'token' prefix also works for personal access tokens. Using 'Bearer' is more standard for OAuth flows.

Can I use a different environment variable name?

Yes, but ensure all implementations use the same variable name for consistency. Update the code accordingly if you change the variable name.

What if the API returns a non-201 status?

The code checks for success status codes (2xx). Adjust the error handling if the API uses different success codes (e.g., 200).

How do I handle pagination or rate limits?

These examples focus on the basic request. For production code, implement retry logic with exponential backoff and check RateLimit headers (X-RateLimit-Remaining, X-RateLimit-Reset).