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/actions/workflows/main.yml/dispatches -H "Authorization: token ghp_abcdefghijklmnopqrstuvwxyz" -d '{"ref":"main","inputs":{"param1":"value1"}}'

Python · requests

import os
import requests

url = f"https://api.github.com/repos/{os.environ['GITHUB_OWNER']}/repo/actions/workflows/main.yml/dispatches"
headers = {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"}
data = {"ref": "main", "inputs": {"param1": "value1"}}

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']}/repo/actions/workflows/main.yml/dispatches"
headers = {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"}
data = {"ref": "main", "inputs": {"param1": "value1"}}

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 = `https://api.github.com/repos/${env.GITHUB_OWNER}/repo/actions/workflows/main.yml/dispatches`;
const headers = { 'Authorization': `Bearer ${env.GITHUB_TOKEN}` };
const data = { ref: 'main', inputs: { param1: 'value1' } };

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 { env } from 'process';

const url = `https://api.github.com/repos/${env.GITHUB_OWNER}/repo/actions/workflows/main.yml/dispatches`;
const headers = { 'Authorization': `Bearer ${env.GITHUB_TOKEN}` };
const data = { ref: 'main', inputs: { param1: 'value1' } };

axios.post(url, data, { headers })
  .then(res => {
    if (res.status >= 400) throw new Error(`HTTP error! status: ${res.status}`);
    console.log(res.data);
  })
  .catch(console.error);

Go · net/http

package main

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

func main() {
	url := fmt.Sprintf("https://api.github.com/repos/%s/repo/actions/workflows/main.yml/dispatches", os.Getenv("GITHUB_OWNER"))
	token := os.Getenv("GITHUB_TOKEN")
	
	data := map[string]interface{}{
		"ref": "main",
		"inputs": map[string]string{"param1": "value1"},
	}
	body, _ := json.Marshal(data)
	
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	if err != nil {
		log.Fatal(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 {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	
	if resp.StatusCode >= 400 {
		log.Fatalf("HTTP error! 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/repo/actions/workflows/main.yml/dispatches',
    urlencode(getenv('GITHUB_OWNER'))
);
$token = getenv('GITHUB_TOKEN');

$data = [
    'ref' => 'main',
    'inputs' => ['param1' => 'value1']
];

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

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

if ($http_response_header[0] !== 'HTTP/1.1 204 No Content') {
    throw new Exception('HTTP error: ' . $http_response_header[0]);
}

print_r(json_decode($result, true));
?>

Ruby · net/http

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

uri = URI.parse("https://api.github.com/repos/#{ENV['GITHUB_OWNER']}/repo/actions/workflows/main.yml/dispatches")
token = ENV['GITHUB_TOKEN']

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

request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{token}"
request['Content-Type'] = 'application/json'
request.body = { ref: 'main', inputs: { param1: 'value1' } }.to_json

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 owner = ProcessInfo.processInfo.environment["GITHUB_OWNER"] ?? ""
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""

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

let body: [String: Any] = [
    "ref": "main",
    "inputs": ["param1": "value1"]
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError(error.localizedDescription)
    }
    guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \(String(describing: response))")
    }
    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;
use std::collections::HashMap;
use std::env;

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

    let url = format!(
        "https://api.github.com/repos/{}/repo/actions/workflows/main.yml/dispatches",
        owner
    );

    let mut map = HashMap::new();
    map.insert("ref", "main");
    let mut inputs = HashMap::new();
    inputs.insert("param1", "value1");
    map.insert("inputs", inputs);

    let client = reqwest::Client::new();
    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", token))
        .json(&map)
        .send()
        .await?;

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

    let body = response.json::<serde_json::Value>().await?;
    println!("{:?}", body);
    Ok(())
}

C# · HttpClient

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var owner = Environment.GetEnvironmentVariable("GITHUB_OWNER");
        var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
        
        var url = $"https://api.github.com/repos/{owner}/repo/actions/workflows/main.yml/dispatches";
        var data = new Dictionary<string, object>
        {
            { "ref", "main" },
            { "inputs", new Dictionary<string, string> { { "param1", "value1" } } }
        };
        
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        
        var response = await client.PostAsJsonAsync(url, data);
        
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }
        
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
    }
}

Translation notes

  • All implementations read secrets from environment variables (GITHUB_OWNER, GITHUB_TOKEN).
  • Python, Node.js, Go, Ruby, Swift, Rust, and C# use idiomatic HTTP clients.
  • PHP uses stream wrappers for simplicity.
  • Error handling checks HTTP status codes and raises exceptions where appropriate.
  • JSON bodies are constructed as objects/dicts, not raw strings.

Common pitfalls when porting

  • Forgetting to set Content-Type header in raw HTTP clients (Go, PHP).
  • Not URL-encoding the owner name in PHP (though GitHub usernames are typically URL-safe).
  • Assuming the API always returns JSON (some APIs may return plain text or XML).
  • Ignoring rate limits or authentication errors in production code.
  • Not handling network timeouts in async languages (Rust, Swift).

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 the original 'token' prefix?

GitHub's API now prefers the 'Bearer' scheme for OAuth tokens, though 'token' still works. Using 'Bearer' is more standard and future-proof.

Can I use a different environment variable name?

Yes, but ensure consistency across all environments. Common alternatives include GITHUB_API_TOKEN or GITHUB_AUTH_TOKEN.

What if the API returns a non-JSON response?

Check the Content-Type header. If it's not JSON, read the response body as text or handle it accordingly.