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/workflow_id/dispatches \
  -H "Authorization: token ghp_1234567890" \
  -H "Accept: application/vnd.github+json" \
  -d '{"ref":"main"}'

Python · requests

import os
import requests

owner = os.environ.get("OWNER")
repo = os.environ.get("REPO")
workflow_id = os.environ.get("WORKFLOW_ID")
token = os.environ.get("GITHUB_TOKEN")

url = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"
headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/vnd.github+json"
}
data = {"ref": "main"}

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

if response.status_code >= 400:
    print(f"Error: {response.status_code} - {response.text}")
else:
    print(response.json())

Python · httpx

import os
import httpx

owner = os.environ.get("OWNER")
repo = os.environ.get("REPO")
workflow_id = os.environ.get("WORKFLOW_ID")
token = os.environ.get("GITHUB_TOKEN")

url = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"
headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/vnd.github+json"
}
data = {"ref": "main"}

try:
    with httpx.Client() as client:
        response = client.post(url, headers=headers, json=data)
        response.raise_for_status()
        print(response.json())
except httpx.HTTPStatusError as e:
    print(f"Error: {e.response.status_code} - {e.response.text}")

Node.js · fetch

const fetch = require('node-fetch');

const owner = process.env.OWNER;
const repo = process.env.REPO;
const workflowId = process.env.WORKFLOW_ID;
const token = process.env.GITHUB_TOKEN;

const url = `https://api.github.com/repos/${owner}/${repo}/actions/workflows/${workflowId}/dispatches`;
const headers = {
  'Authorization': `Bearer ${token}`,
  'Accept': 'application/vnd.github+json'
};
const data = { ref: 'main' };

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Node.js · axios

const axios = require('axios');

const owner = process.env.OWNER;
const repo = process.env.REPO;
const workflowId = process.env.WORKFLOW_ID;
const token = process.env.GITHUB_TOKEN;

const url = `https://api.github.com/repos/${owner}/${repo}/actions/workflows/${workflowId}/dispatches`;
const headers = {
  'Authorization': `Bearer ${token}`,
  'Accept': 'application/vnd.github+json'
};
const data = { ref: 'main' };

axios.post(url, data, { headers })
  .then(response => {
    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 DispatchRequest struct {
	Ref string `json:"ref"`
}

func main() {
	owner := os.Getenv("OWNER")
	repo := os.Getenv("REPO")
	workflowID := os.Getenv("WORKFLOW_ID")
	token := os.Getenv("GITHUB_TOKEN")

	url := fmt.Sprintf("https://api.github.com/repos/%s/%s/actions/workflows/%s/dispatches", owner, repo, workflowID)
	data := DispatchRequest{Ref: "main"}
	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

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

	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Accept", "application/vnd.github+json")

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

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	if resp.StatusCode >= 400 {
		fmt.Printf("Error: %d - %s\n", resp.StatusCode, string(body))
	} else {
		fmt.Println(string(body))
	}
}

PHP · cURL

<?php

$owner = getenv('OWNER');
$repo = getenv('REPO');
$workflowId = getenv('WORKFLOW_ID');
$token = getenv('GITHUB_TOKEN');

$url = "https://api.github.com/repos/{$owner}/{$repo}/actions/workflows/{$workflowId}/dispatches";
$data = ['ref' => 'main'];

$options = [
    'http' => [
        'header' => [
            "Authorization: Bearer {$token}",
            "Accept: application/vnd.github+json",
            "Content-Type: application/json"
        ],
        '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 204 No Content') {
    echo "Error: " . $http_response_header[0] . " - " . $response . "\n";
} else {
    echo $response . "\n";
}

Ruby · net/http

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

owner = ENV['OWNER']
repo = ENV['REPO']
workflow_id = ENV['WORKFLOW_ID']
token = ENV['GITHUB_TOKEN']

uri = URI.parse("https://api.github.com/repos/#{[owner, repo].join('/')}/actions/workflows/#{[workflow_id]}/dispatches")
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{token}"
request['Accept'] = 'application/vnd.github+json'
request.body = { ref: 'main' }.to_json

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

response = http.request(request)

if response.code.to_i >= 400
  puts "Error: #{response.code} - #{response.body}"
else
  puts response.body
end

Swift · URLSession

import Foundation

let owner = ProcessInfo.processInfo.environment["OWNER"] ?? ""
let repo = ProcessInfo.processInfo.environment["REPO"] ?? ""
let workflowId = ProcessInfo.processInfo.environment["WORKFLOW_ID"] ?? ""
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""

let url = URL(string: "https://api.github.com/repos/" + owner + "/" + repo + "/actions/workflows/" + workflowId + "/dispatches")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
request.httpBody = try? JSONSerialization.data(withJSONObject: ["ref": "main"])

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
    }
    if httpResponse.statusCode >= 400 {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print("Error: \(httpResponse.statusCode) - \(responseBody)")
        }
    } else {
        if let data = data {
            print(String(data: data, encoding: .utf8) ?? "")
        }
    }
}
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 owner = env::var("OWNER")?;
    let repo = env::var("REPO")?;
    let workflow_id = env::var("WORKFLOW_ID")?;
    let token = env::var("GITHUB_TOKEN")?;

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

    let client = Client::new();
    let response = client
        .post(&url)
        .header("Authorization", format!("Bearer {}", token))
        .header("Accept", "application/vnd.github+json")
        .json(&json!({"ref": "main"}))
        .send()?;

    if !response.status().is_success() {
        eprintln!("Error: {} - {}", response.status(), response.text()?);
    } else {
        println!("{}", response.text()?);
    }

    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 owner = Environment.GetEnvironmentVariable("OWNER");
        var repo = Environment.GetEnvironmentVariable("REPO");
        var workflowId = Environment.GetEnvironmentVariable("WORKFLOW_ID");
        var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");

        var url = $"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflowId}/dispatches";
        var data = new { @ref = "main" };

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));

        var response = await client.PostAsJsonAsync(url, data);

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
        }
        else
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseContent);
        }
    }
}

Translation notes

  • All implementations use environment variables for secrets (OWNER, REPO, WORKFLOW_ID, GITHUB_TOKEN).
  • Bearer token is constructed dynamically from the environment variable GITHUB_TOKEN.
  • Error handling checks HTTP status codes and prints error messages if present.
  • JSON bodies are sent as structured objects, not raw strings.
  • All libraries handle HTTPS natively and do not require manual SSL configuration.

Common pitfalls when porting

  • Forgetting to set environment variables before running the code will cause failures.
  • Not handling HTTP errors properly may lead to unhandled exceptions or silent failures.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task must be started with task.resume().
  • In Rust, the blocking client is used for simplicity; async is recommended for production.
  • In PHP, file_get_contents may not be suitable for all environments due to security restrictions.

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 tokens, though 'token' still works. Using 'Bearer' is more standard and future-proof.

Can I use a different HTTP client library in these languages?

Yes, but ensure it supports HTTPS, custom headers, and JSON serialization. The examples use the most idiomatic clients for simplicity.

How do I set the environment variables?

For local testing, use export OWNER=myuser in bash or set OWNER=myuser in Windows cmd. In production, use your deployment platform's secrets management.

Why is the Go example using a blocking client?

The blocking client is simpler for demonstration. In production Go code, consider using the async http.Client for better performance.