import os
import requests
url = "https://api.github.com/repos/owner/repo/git/refs"
headers = {
"Authorization": f"Bearer {os.environ.get('GITHUB_TOKEN')}"
}
data = {
"ref": "refs/heads/feature-branch",
"sha": "1234567890abcdef1234567890abcdef12345678"
}
response = requests.post(url, headers=headers, json=data)
if response.status_code != 201:
print(f"Error: {response.status_code} - {response.text}")
else:
print(response.json())
import os
import httpx
url = "https://api.github.com/repos/owner/repo/git/refs"
headers = {
"Authorization": f"Bearer {os.environ.get('GITHUB_TOKEN')}"
}
data = {
"ref": "refs/heads/feature-branch",
"sha": "1234567890abcdef1234567890abcdef12345678"
}
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
if response.status_code != 201:
print(f"Error: {response.status_code} - {response.text}")
else:
print(response.json())
import fetch from 'node-fetch';
import { config } from 'dotenv';
config();
const url = 'https://api.github.com/repos/owner/repo/git/refs';
const headers = {
'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`
};
const body = JSON.stringify({
ref: 'refs/heads/feature-branch',
sha: '1234567890abcdef1234567890abcdef12345678'
});
fetch(url, {
method: 'POST',
headers,
body
})
.then(res => {
if (!res.ok) {
throw new Error(`Error: ${res.status} - ${res.text()}`);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
import axios from 'axios';
import { config } from 'dotenv';
config();
const url = 'https://api.github.com/repos/owner/repo/git/refs';
const headers = {
'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`
};
const data = {
ref: 'refs/heads/feature-branch',
sha: '1234567890abcdef1234567890abcdef12345678'
};
axios.post(url, data, { headers })
.then(response => {
if (response.status !== 201) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
console.log(response.data);
})
.catch(error => {
console.error(error.message);
});
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
type Ref struct {
Ref string `json:"ref"`
Sha string `json:"sha"`
}
func main() {
url := "https://api.github.com/repos/owner/repo/git/refs"
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
fmt.Println("GITHUB_TOKEN environment variable not set")
return
}
data := Ref{
Ref: "refs/heads/feature-branch",
Sha: "1234567890abcdef1234567890abcdef12345678",
}
body, _ := json.Marshal(data)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Error: %d - %s\n", resp.StatusCode, string(body))
return
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
<?php
$url = 'https://api.github.com/repos/owner/repo/git/refs';
$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
die('GITHUB_TOKEN environment variable not set');
}
$data = [
'ref' => 'refs/heads/feature-branch',
'sha' => '1234567890abcdef1234567890abcdef12345678'
];
$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') {
echo "Error: " . $http_response_header[0] . " - " . $response . "\n";
} else {
echo $response;
}
require 'net/http'
require 'json'
require 'uri'
url = URI.parse('https://api.github.com/repos/owner/repo/git/refs')
token = ENV.fetch('GITHUB_TOKEN') { raise 'GITHUB_TOKEN environment variable not set' }
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.path, {
'Authorization' => "Bearer #{token}",
'Content-Type' => 'application/json'
})
request.body = {
ref: 'refs/heads/feature-branch',
sha: '1234567890abcdef1234567890abcdef12345678'
}.to_json
response = http.request(request)
if response.code != '201'
puts "Error: #{response.code} - #{response.body}"
else
puts JSON.parse(response.body)
end
import Foundation
let url = URL(string: "https://api.github.com/repos/owner/repo/git/refs")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""
if token.isEmpty {
fatalError("GITHUB_TOKEN environment variable not set")
}
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"ref": "refs/heads/feature-branch",
"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: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse else {
print("Invalid response")
return
}
if httpResponse.statusCode != 201 {
if let data = data, let responseBody = String(data: data, encoding: .utf8) {
print("Error: \(httpResponse.statusCode) - \(responseBody)")
}
return
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::env;
use reqwest::blocking::Client;
use serde_json::json;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://api.github.com/repos/owner/repo/git/refs";
let token = env::var("GITHUB_TOKEN")?;
let client = Client::new();
let body = json!({
"ref": "refs/heads/feature-branch",
"sha": "1234567890abcdef1234567890abcdef12345678"
});
let response = client
.post(url)
.header("Authorization", format!("Bearer {}", token))
.json(&body)
.send()?;
if !response.status().is_success() {
eprintln!("Error: {} - {}", response.status(), response.text()?);
} else {
println!("{:?}", response.json::<serde_json::Value>()?);
}
Ok(())
}
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 url = "https://api.github.com/repos/owner/repo/git/refs";
var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
if (string.IsNullOrEmpty(token))
{
Console.WriteLine("GITHUB_TOKEN environment variable not set");
return;
}
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var body = new
{
@ref = "refs/heads/feature-branch",
sha = "1234567890abcdef1234567890abcdef12345678"
};
var response = await client.PostAsJsonAsync(url, body);
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
}
else
{
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
}
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> PostAsJsonAsync<T>(
this HttpClient client, string url, T data)
{
var content = new StringContent(JsonSerializer.Serialize(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return await client.PostAsync(url, content);
}
}