Qaynaq LABS · TOOLS

CURL → CODE · PUT · BEARER

cURL → 10 languages

PUT api.github.com · body: json · secrets replaced with env vars.

Source cURL
curl -X PUT https://api.github.com/repos/owner/repo/contents/path/to/file.txt \
  -H "Authorization: token ghp_1234567890" \
  -H "Accept: application/vnd.github.v3+json" \
  -d '{"message":"Update file","content":"bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=","sha":"1234567890abcdef1234567890abcdef12345678"}'

Python · requests

import os
import requests

url = f"https://api.github.com/repos/{os.environ['OWNER']}/repo/contents/path/to/file.txt"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "message": "Update file",
    "content": "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
    "sha": "1234567890abcdef1234567890abcdef12345678"
}

response = requests.put(url, headers=headers, json=data)
if response.status_code >= 400:
    print(response.text)
else:
    print(response.json())

Python · httpx

import os
import httpx

url = f"https://api.github.com/repos/{os.environ['OWNER']}/repo/contents/path/to/file.txt"
headers = {
    "Authorization": f"token {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github.v3+json"
}
data = {
    "message": "Update file",
    "content": "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
    "sha": "1234567890abcdef1234567890abcdef12345678"
}

with httpx.Client() as client:
    response = client.put(url, headers=headers, json=data)
    if response.status_code >= 400:
        print(response.text)
    else:
        print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'process';

const url = `https://api.github.com/repos/${env.OWNER}/repo/contents/path/to/file.txt`;
const headers = {
  "Authorization": `token ${env.GITHUB_TOKEN}`,
  "Accept": "application/vnd.github.v3+json"
};
const data = {
  message: "Update file",
  content: "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
  sha: "1234567890abcdef1234567890abcdef12345678"
};

fetch(url, {
  method: 'PUT',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (res.status >= 400) {
      return res.text().then(text => { throw new Error(text); });
    }
    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.OWNER}/repo/contents/path/to/file.txt`;
const headers = {
  "Authorization": `token ${env.GITHUB_TOKEN}`,
  "Accept": "application/vnd.github.v3+json"
};
const data = {
  message: "Update file",
  content: "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
  sha: "1234567890abcdef1234567890abcdef12345678"
};

axios.put(url, data, { headers })
  .then(res => {
    if (res.status >= 400) {
      console.error(res.data);
    } else {
      console.log(res.data);
    }
  })
  .catch(console.error);

Go · net/http

package main

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

type RequestBody struct {
	Message string `json:"message"`
	Content string `json:"content"`
	Sha     string `json:"sha"`
}

func main() {
	owner := os.Getenv("OWNER")
	token := os.Getenv("GITHUB_TOKEN")
	url := fmt.Sprintf("https://api.github.com/repos/%s/repo/contents/path/to/file.txt", owner)

	body := RequestBody{
		Message: "Update file",
		Content: "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
		Sha:     "1234567890abcdef1234567890abcdef12345678",
	}

	jsonBody, _ := json.Marshal(body)
	req, _ := http.NewRequest("PUT", url, bytes.NewBuffer(jsonBody))

	req.Header.Set("Authorization", fmt.Sprintf("token %s", token))
	req.Header.Set("Accept", "application/vnd.github.v3+json")

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

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
	} else {
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
	}
}

PHP · cURL

<?php

$owner = getenv('OWNER');
$token = getenv('GITHUB_TOKEN');
$url = "https://api.github.com/repos/{$owner}/repo/contents/path/to/file.txt";

$data = [
    'message' => 'Update file',
    'content' => 'bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=',
    'sha' => '1234567890abcdef1234567890abcdef12345678'
];

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

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

if ($http_response_header[0] >= '400') {
    echo $response;
} else {
    echo $response;
}

?>

Ruby · net/http

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

owner = ENV['OWNER']
token = ENV['GITHUB_TOKEN']
url = URI.parse("https://api.github.com/repos/#{owner}/repo/contents/path/to/file.txt")

body = {
  message: 'Update file',
  content: 'bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=',
  sha: '1234567890abcdef1234567890abcdef12345678'
}.to_json

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

request = Net::HTTP::Put.new(url.request_uri, {
  'Authorization' => "token #{token}",
  'Accept' => 'application/vnd.github.v3+json',
  'Content-Type' => 'application/json'
})
request.body = body

response = http.request(request)

if response.code.to_i >= 400
  puts response.body
else
  puts response.body
end

Swift · URLSession

import Foundation

let owner = ProcessInfo.processInfo.environment["OWNER"] ?? ""
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""
let url = URL(string: "https://api.github.com/repos/" + owner + "/repo/contents/path/to/file.txt")!

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("token " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")

let body: [String: Any] = [
    "message": "Update file",
    "content": "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
    "sha": "1234567890abcdef1234567890abcdef12345678"
]

request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print(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(responseBody)
        }
    } else {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    }
}

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 owner = env::var("OWNER")?;
    let token = env::var("GITHUB_TOKEN")?;
    let url = format!("https://api.github.com/repos/{}/repo/contents/path/to/file.txt", owner);

    let client = Client::new();
    let response = client
        .put(&url)
        .header("Authorization", format!("token {}", token))
        .header("Accept", "application/vnd.github.v3+json")
        .json(&json!({
            "message": "Update file",
            "content": "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
            "sha": "1234567890abcdef1234567890abcdef12345678"
        }))
        .send()?;

    if response.status().is_client_error() || response.status().is_server_error() {
        println!("{}", response.text()?);
    } else {
        println!("{}", response.text()?);
    }

    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var owner = Environment.GetEnvironmentVariable("OWNER");
        var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
        var url = $"https://api.github.com/repos/{owner}/repo/contents/path/to/file.txt";

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

        var body = new {
            message = "Update file",
            content = "bXkgdGV4dCBmaWxlIHdpdGggY29udGVudHM=",
            sha = "1234567890abcdef1234567890abcdef12345678"
        };

        var response = await client.PutAsJsonAsync(url, body);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        else
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
    }
}

Translation notes

  • All implementations use environment variables for secrets (OWNER, GITHUB_TOKEN).
  • Python, Node.js, Go, Ruby, Swift, Rust, and C# use idiomatic HTTP clients.
  • PHP uses the built-in stream context for simplicity.
  • Error handling checks status codes >= 400 and prints the response body.
  • JSON bodies are constructed as objects/dicts, not raw strings.

Common pitfalls when porting

  • Forgetting to set the Accept header may result in GitHub API returning HTML instead of JSON.
  • Not using HTTPS can expose the token in transit.
  • Hardcoding secrets in code instead of using environment variables.
  • Ignoring SSL certificate validation in Go or other languages (not shown here but important in production).
  • Assuming the request body is always JSON; GitHub API may return errors if Content-Type is incorrect.

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?

Environment variables separate configuration from code, reducing the risk of accidental exposure (e.g., in version control).

How do I handle pagination in GitHub API responses?

GitHub API responses include Link headers for pagination. Use the 'next' URL to fetch subsequent pages.

Why does the Go example use bytes.NewBuffer?

Go's http.NewRequest requires an io.Reader for the body. bytes.NewBuffer converts the JSON byte slice to a reader.

How do I set a custom timeout in these clients?

Most clients allow setting timeouts via constructor or method (e.g., Python's requests: timeout=10, Go's http.Client: Timeout field).