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.yml/dispatches \
  -H "Authorization: token ghp_1234567890" \
  -H "Accept: application/vnd.github.v3+json" \
  -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/workflow.yml/dispatches"
headers = {
    "Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
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/workflow.yml/dispatches"
headers = {
    "Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
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/workflow.yml/dispatches`;
const headers = {
  'Authorization': `Bearer ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github.v3+json'
};
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/workflow.yml/dispatches`;
const headers = {
  'Authorization': `Bearer ${env.GITHUB_TOKEN}`,
  'Accept': 'application/vnd.github.v3+json'
};
const data = {
  ref: 'main',
  inputs: {
    param1: 'value1'
  }
};

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 DispatchRequest struct {
	Ref    string            `json:"ref"`
	Inputs map[string]string `json:"inputs"`
}

func main() {
	owner := os.Getenv("GITHUB_OWNER")
	token := os.Getenv("GITHUB_TOKEN")
	
	url := fmt.Sprintf("https://api.github.com/repos/%s/repo/actions/workflows/workflow.yml/dispatches", owner)
	data := DispatchRequest{
		Ref:    "main",
		Inputs: map[string]string{"param1": "value1"},
	}
	
	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.v3+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

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

$url = "https://api.github.com/repos/{$owner}/repo/actions/workflows/workflow.yml/dispatches";
$data = [
    'ref' => 'main',
    'inputs' => [
        'param1' => 'value1'
    ]
];

$options = [
    'http' => [
        'header' => [
            "Authorization: Bearer {$token}",
            "Accept: application/vnd.github.v3+json"
        ],
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

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

if ($result === false) {
    throw new Exception("Request failed");
}

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

Ruby · net/http

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

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

uri = URI.parse("https://api.github.com/repos/#{owner}/repo/actions/workflows/workflow.yml/dispatches")
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['Accept'] = 'application/vnd.github.v3+json'
request.body = {
  ref: 'main',
  inputs: {
    param1: 'value1'
  }
}.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 token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""

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

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 {
        print("Error: \(error)")
        return
    }
    
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 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::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;

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/workflow.yml/dispatches",
        owner
    );

    let mut headers = header::HeaderMap::new();
    headers.insert(
        "Authorization",
        header::HeaderValue::from_str(&format!("Bearer {}", token))?,
    );
    headers.insert(
        "Accept",
        header::HeaderValue::from_static("application/vnd.github.v3+json"),
    );

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

    let body = serde_json::json!({
        "ref": "main",
        "inputs": inputs
    });

    let client = Client::new();
    let response = client
        .post(&url)
        .headers(headers)
        .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.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(string[] args)
    {
        var owner = Environment.GetEnvironmentVariable("GITHUB_OWNER");
        var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");

        var url = $"https://api.github.com/repos/{owner}/repo/actions/workflows/workflow.yml/dispatches";
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

        var body = new
        {
            @ref = "main",
            inputs = new Dictionary<string, string> { { "param1", "value1" } }
        };

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

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

public static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PostAsJsonAsync<T>(
        this HttpClient httpClient, string url, T data)
    {
        var content = new StringContent(JsonSerializer.Serialize(data));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        return await httpClient.PostAsync(url, content);
    }
}

Translation notes

  • Bearer token is read from GITHUB_TOKEN environment variable
  • GitHub owner is read from GITHUB_OWNER environment variable
  • All implementations use idiomatic HTTP clients for their respective languages
  • JSON bodies are sent as structured objects, not raw strings
  • Error handling checks HTTP status and reads response body
  • Environment variables are used for secrets (never inline)
  • URL path parameters are interpolated from environment variables

Common pitfalls when porting

  • Forgetting to set the Accept header may result in different API responses
  • Not using HTTPS can expose the bearer token
  • Hardcoding secrets in code instead of using environment variables
  • Ignoring HTTP status codes can lead to silent failures
  • Not properly escaping URL path parameters can cause malformed requests

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

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

Can I use a personal access token (PAT) instead of a GitHub token?

Yes, GitHub personal access tokens work the same way as OAuth tokens for this API endpoint.

What happens if the workflow file doesn't exist?

The API will return a 404 Not Found response with an error message indicating the workflow file was not found.