import os
import requests
url = "https://api.github.com/repos/octocat/Hello-World/issues"
headers = {
"Authorization": f"token {os.environ['GITHUB_TOKEN']}",
"Accept": "application/vnd.github.v3+json"
}
data = {
"title": "New issue",
"body": "Please fix this."
}
response = requests.post(url, headers=headers, json=data)
if response.status_code >= 400:
print(f"Error: {response.status_code} - {response.text}")
else:
print(response.json())
import os
import httpx
url = "https://api.github.com/repos/octocat/Hello-World/issues"
headers = {
"Authorization": f"token {os.environ['GITHUB_TOKEN']}",
"Accept": "application/vnd.github.v3+json"
}
data = {
"title": "New issue",
"body": "Please fix this."
}
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
if response.status_code >= 400:
print(f"Error: {response.status_code} - {response.text}")
else:
print(response.json())
import fetch from 'node-fetch';
import { env } from 'process';
const url = 'https://api.github.com/repos/octocat/Hello-World/issues';
const headers = {
'Authorization': `token ${env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json'
};
const data = {
title: 'New issue',
body: 'Please fix this.'
};
fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(data)
})
.then(res => {
if (res.status >= 400) {
throw new Error(`Error: ${res.status} - ${res.text}`);
}
return res.json();
})
.then(console.log)
.catch(console.error);
import axios from 'axios';
import { env } from 'process';
const url = 'https://api.github.com/repos/octocat/Hello-World/issues';
const headers = {
'Authorization': `token ${env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json'
};
const data = {
title: 'New issue',
body: 'Please fix this.'
};
axios.post(url, data, { headers })
.then(res => {
if (res.status >= 400) {
throw new Error(`Error: ${res.status} - ${res.data}`);
}
console.log(res.data);
})
.catch(console.error);
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Issue struct {
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
url := "https://api.github.com/repos/octocat/Hello-World/issues"
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
log.Fatal("GITHUB_TOKEN environment variable not set")
}
data := Issue{
Title: "New issue",
Body: "Please fix this.",
}
body, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "token "+token)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
log.Fatalf("Error: %d - %s", resp.StatusCode, string(body))
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
<?php
$url = 'https://api.github.com/repos/octocat/Hello-World/issues';
$token = getenv('GITHUB_TOKEN');
if (empty($token)) {
die('GITHUB_TOKEN environment variable not set');
}
$data = [
'title' => 'New issue',
'body' => 'Please fix this.'
];
$options = [
'http' => [
'header' => [
"Authorization: token $token",
"Accept: application/vnd.github.v3+json",
"Content-Type: application/json"
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($http_response_header[0] === 'HTTP/1.1 201 Created' || $http_response_header[0] === 'HTTP/2 201') {
echo $response;
} else {
echo "Error: " . $http_response_header[0] . " - " . $response;
}
require 'net/http'
require 'json'
require 'uri'
url = URI.parse('https://api.github.com/repos/octocat/Hello-World/issues')
token = ENV.fetch('GITHUB_TOKEN') { raise 'GITHUB_TOKEN environment variable not set' }
data = {
title: 'New issue',
body: 'Please fix this.'
}
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.request_uri)
request['Authorization'] = "token #{token}"
request['Accept'] = 'application/vnd.github.v3+json'
request.body = data.to_json
response = http.request(request)
if response.code.to_i >= 400
puts "Error: #{response.code} - #{response.body}"
else
puts JSON.parse(response.body)
end
import Foundation
let url = URL(string: "https://api.github.com/repos/octocat/Hello-World/issues")!
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? { fatalError("GITHUB_TOKEN environment variable not set") }()
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"title": "New issue",
"body": "Please fix this."
]
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
}
guard (200...299).contains(httpResponse.statusCode) else {
print("Error: \(httpResponse.statusCode) - \(String(data: data ?? Data(), encoding: .utf8) ?? "")")
return
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://api.github.com/repos/octocat/Hello-World/issues";
let token = env::var("GITHUB_TOKEN")?;
let mut headers = header::HeaderMap::new();
headers.insert(
"Authorization",
header::HeaderValue::from_str(&format!("token {}", token))?,
);
headers.insert(
"Accept",
header::HeaderValue::from_static("application/vnd.github.v3+json"),
);
let client = Client::new();
let mut body = HashMap::new();
body.insert("title", "New issue");
body.insert("body", "Please fix this.");
let response = client
.post(url)
.headers(headers)
.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.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()
{
var url = "https://api.github.com/repos/octocat/Hello-World/issues";
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("token", token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
var body = new Dictionary<string, string>
{
{ "title", "New issue" },
{ "body", "Please fix this." }
};
var response = await client.PostAsJsonAsync(url, body);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
}
else
{
var result = await response.Content.ReadFromJsonAsync<Dictionary<string, object>>();
Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
}
}
}