import os
import requests
url = f"https://api.github.com/repos/{os.environ['GITHUB_OWNER']}/{os.environ['GITHUB_REPO']}/keys"
headers = {
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
"Accept": "application/vnd.github+json"
}
data = {
"title": "my-key",
"key": "ssh-rsa AAA..."
}
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import os
import httpx
url = f"https://api.github.com/repos/{os.environ['GITHUB_OWNER']}/{os.environ['GITHUB_REPO']}/keys"
headers = {
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
"Accept": "application/vnd.github+json"
}
data = {
"title": "my-key",
"key": "ssh-rsa AAA..."
}
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import fetch from 'node-fetch';
import { env } from 'process';
const url = `https://api.github.com/repos/${env.GITHUB_OWNER}/${env.GITHUB_REPO}/keys`;
const headers = {
"Authorization": `Bearer ${env.GITHUB_TOKEN}`,
"Accept": "application/vnd.github+json"
};
const data = {
title: "my-key",
key: "ssh-rsa AAA..."
};
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);
import axios from 'axios';
import { env } from 'process';
const url = `https://api.github.com/repos/${env.GITHUB_OWNER}/${env.GITHUB_REPO}/keys`;
const headers = {
"Authorization": `Bearer ${env.GITHUB_TOKEN}`,
"Accept": "application/vnd.github+json"
};
const data = {
title: "my-key",
key: "ssh-rsa AAA..."
};
axios.post(url, data, { headers })
.then(res => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
)
func main() {
owner := os.Getenv("GITHUB_OWNER")
repo := os.Getenv("GITHUB_REPO")
token := os.Getenv("GITHUB_TOKEN")
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/keys", owner, repo)
payload := strings.NewReader(`{"title":"my-key","key":"ssh-rsa AAA..."}`)
req, err := http.NewRequest("POST", url, payload)
if err != nil {
log.Fatal(err)
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("Accept", "application/vnd.github+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)
}
// Optionally read and print response body
// body, _ := io.ReadAll(resp.Body)
// fmt.Println(string(body))
}
<?php
$owner = getenv('GITHUB_OWNER');
$repo = getenv('GITHUB_REPO');
$token = getenv('GITHUB_TOKEN');
$url = "https://api.github.com/repos/{$owner}/{$repo}/keys";
$data = [
'title' => 'my-key',
'key' => 'ssh-rsa AAA...'
];
$options = [
'http' => [
'header' => [
"Authorization: Bearer {$token}",
"Accept: application/vnd.github+json",
"Content-Type: application/json"
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$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);
require 'net/http'
require 'json'
require 'uri'
owner = ENV['GITHUB_OWNER']
repo = ENV['GITHUB_REPO']
token = ENV['GITHUB_TOKEN']
uri = URI.parse("https://api.github.com/repos/#{[owner, repo].join('/')}/keys")
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+json'
request.body = { title: 'my-key', key: 'ssh-rsa AAA...' }.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "Request failed: #{response.code} #{response.message}"
end
puts JSON.parse(response.body)
import Foundation
let owner = ProcessInfo.processInfo.environment["GITHUB_OWNER"] ?? ""
let repo = ProcessInfo.processInfo.environment["GITHUB_REPO"] ?? ""
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""
let url = URL(string: "https://api.github.com/repos/" + owner + "/" + repo + "/keys")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
let body: [String: Any] = [
"title": "my-key",
"key": "ssh-rsa AAA..."
]
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")
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 owner = env::var("GITHUB_OWNER")?;
let repo = env::var("GITHUB_REPO")?;
let token = env::var("GITHUB_TOKEN")?;
let url = format!("https://api.github.com/repos/{}/{}/keys", owner, repo);
let client = Client::new();
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", token))
.header("Accept", "application/vnd.github+json")
.json(&json!({"title": "my-key", "key": "ssh-rsa AAA..."}))
.send()?;
if !response.status().is_success() {
return Err("Request failed".into());
}
let body = response.text()?;
println!("{}", body);
Ok(())
}
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("GITHUB_OWNER");
var repo = Environment.GetEnvironmentVariable("GITHUB_REPO");
var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
var url = $"https://api.github.com/repos/{owner}/{repo}/keys";
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
var content = new {
title = "my-key",
key = "ssh-rsa AAA..."
};
var response = await client.PostAsJsonAsync(url, content);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}