import os
import requests
url = "https://api.github.com/user/repos"
headers = {
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
"Accept": "application/vnd.github+json"
}
data = {
"name": "my-new-repo",
"private": False,
"description": "A new repository created via API"
}
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())
import os
import httpx
url = "https://api.github.com/user/repos"
headers = {
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
"Accept": "application/vnd.github+json"
}
data = {
"name": "my-new-repo",
"private": False,
"description": "A new repository created via API"
}
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 process from 'process';
const url = 'https://api.github.com/user/repos';
const headers = {
'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github+json'
};
const data = {
name: 'my-new-repo',
private: false,
description: 'A new repository created via API'
};
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 process from 'process';
const url = 'https://api.github.com/user/repos';
const headers = {
'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github+json'
};
const data = {
name: 'my-new-repo',
private: false,
description: 'A new repository created via API'
};
axios.post(url, data, { headers })
.then(res => {
console.log(res.data);
})
.catch(err => {
console.error(err.message);
});
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
type Repo struct {
Name string `json:"name"`
Private bool `json:"private"`
Description string `json:"description"`
}
func main() {
url := "https://api.github.com/user/repos"
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
fmt.Println("GITHUB_TOKEN environment variable not set")
return
}
data := Repo{
Name: "my-new-repo",
Private: false,
Description: "A new repository created via API",
}
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("Accept", "application/vnd.github+json")
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.StatusOK {
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Request failed with status %d: %s\n", resp.StatusCode, string(body))
return
}
body, _ = io.ReadAll(resp.Body)
fmt.Println(string(body))
}
<?php
$url = 'https://api.github.com/user/repos';
$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
die('GITHUB_TOKEN environment variable not set');
}
$data = [
'name' => 'my-new-repo',
'private' => false,
'description' => 'A new repository created via API'
];
$options = [
'http' => [
'method' => 'POST',
'header' => [
'Authorization: Bearer ' . $token,
'Accept: application/vnd.github+json',
'Content-Type: application/json'
],
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
$error = error_get_last();
die('Request failed: ' . $error['message']);
}
$response = json_decode($result, true);
print_r($response);
require 'net/http'
require 'json'
require 'uri'
url = URI.parse('https://api.github.com/user/repos')
token = ENV.fetch('GITHUB_TOKEN') { raise 'GITHUB_TOKEN environment variable not set' }
data = {
name: 'my-new-repo',
private: false,
description: 'A new repository created via API'
}
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.path, {
'Authorization' => "Bearer #{token}",
'Accept' => 'application/vnd.github+json',
'Content-Type' => 'application/json'
})
request.body = data.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
puts "Request failed with status #{response.code}: #{response.body}"
exit 1
end
puts response.body
import Foundation
let url = URL(string: "https://api.github.com/user/repos")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"name": "my-new-repo",
"private": false,
"description": "A new repository created via API"
]
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()
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/user/repos";
let token = env::var("GITHUB_TOKEN")?;
let client = Client::new();
let body = json!({
"name": "my-new-repo",
"private": false,
"description": "A new repository created via API"
});
let response = client
.post(url)
.header("Authorization", format!("Bearer {}", token))
.header("Accept", "application/vnd.github+json")
.json(&body)
.send()?;
if !response.status().is_success() {
eprintln!("Request failed with status: {}", response.status());
return Ok(());
}
let json: serde_json::Value = response.json()?;
println!("{}", json);
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/user/repos";
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);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
var data = new
{
name = "my-new-repo",
@private = false,
description = "A new repository created via API"
};
var response = await client.PostAsJsonAsync(url, data);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Request failed with status {response.StatusCode}");
return;
}
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);
}
}
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);
}
}