Qaynaq LABS · TOOLS

CURL → CODE · GET · BEARER

cURL → 10 languages

GET api.sendgrid.com · secrets replaced with env vars.

Source cURL
curl -X GET https://api.sendgrid.com/v3/alerts/settings \
  -H "Authorization: Bearer SG.1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Content-Type: application/json"

Python · requests

import os
import requests

response = requests.get(
    "https://api.sendgrid.com/v3/alerts/settings",
    headers={
        "Authorization": f"Bearer {os.environ['SENDGRID_API_KEY']}",
        "Content-Type": "application/json"
    }
)

if response.status_code != 200:
    raise Exception(f"Request failed with status {response.status_code}: {response.text}")

print(response.json())

Python · httpx

import os
import httpx

with httpx.Client() as client:
    response = client.get(
        "https://api.sendgrid.com/v3/alerts/settings",
        headers={
            "Authorization": f"Bearer {os.environ['SENDGRID_API_KEY']}",
            "Content-Type": "application/json"
        }
    )

    if response.status_code != 200:
        raise Exception(f"Request failed with status {response.status_code}: {response.text}")

    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://api.sendgrid.com/v3/alerts/settings', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${process.env.SENDGRID_API_KEY}`,
    'Content-Type': 'application/json'
  }
});

if (!response.ok) {
  throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
}

const data = await response.json();
console.log(data);

Node.js · axios

import axios from 'axios';

try {
  const response = await axios.get('https://api.sendgrid.com/v3/alerts/settings', {
    headers: {
      'Authorization': `Bearer ${process.env.SENDGRID_API_KEY}`,
      'Content-Type': 'application/json'
    }
  });

  if (response.status !== 200) {
    throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
  }

  console.log(response.data);
} catch (error) {
  console.error('Error:', error.message);
}

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	req, err := http.NewRequest("GET", "https://api.sendgrid.com/v3/alerts/settings", nil)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Authorization", "Bearer "+os.Getenv("SENDGRID_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("Request failed with status %d: %s", resp.StatusCode, string(body)))
	}

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

PHP · cURL

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.sendgrid.com/v3/alerts/settings');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SENDGRID_API_KEY'),
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    throw new Exception("Request failed with status $httpCode: $response");
}

$decoded = json_decode($response, true);
print_r($decoded);

Ruby · net/http

require 'net/http'
require 'json'

uri = URI('https://api.sendgrid.com/v3/alerts/settings')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{ENV['SENDGRID_API_KEY']}"
req['Content-Type'] = 'application/json'

res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
  http.request(req)
end

unless res.is_a?(Net::HTTPSuccess)
  raise "Request failed with status #{res.code}: #{res.body}"
end

puts JSON.parse(res.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.sendgrid.com/v3/alerts/settings")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["SENDGRID_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        fatalError("Request failed: \(error?.localizedDescription ?? "Unknown error")")
    }

    if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
        fatalError("Request failed with status \(httpResponse.statusCode): \(String(data: data, encoding: .utf8) ?? "")")
    }

    if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest;
use tokio::main;

#[main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = env::var("SENDGRID_API_KEY")?;
    let client = reqwest::Client::new();
    let response = client
        .get("https://api.sendgrid.com/v3/alerts/settings")
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .send()
        .await?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await?;
        return Err(format!("Request failed with status {}: {}", status, body).into());
    }

    let body = response.json::<serde_json::Value>().await?;
    println!("{:?}", body);
    Ok(())
}

C# · HttpClient

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

class Program
{
    static async Task Main()
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Get, "https://api.sendgrid.com/v3/alerts/settings");
        request.Headers.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SENDGRID_API_KEY")}");
        request.Headers.Add("Content-Type", "application/json");

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            throw new Exception($"Request failed with status {response.StatusCode}: {content}");
        }

        var body = await response.Content.ReadAsStringAsync();
        Console.WriteLine(body);
    }
}

Translation notes

  • All implementations use environment variables for the API key (SENDGRID_API_KEY)
  • Error handling checks HTTP status code and reads response body on failure
  • JSON response is parsed where applicable (Python, Node.js, Ruby, Swift, Rust, C#)
  • Go and PHP return raw response body as strings
  • Swift uses async/await pattern with URLSession
  • Rust uses tokio runtime for async operations
  • C# uses HttpClient for modern HTTP requests

Common pitfalls when porting

  • Forgetting to set the SENDGRID_API_KEY environment variable will cause runtime errors
  • In Go, forgetting to close the response body can lead to resource leaks
  • In PHP, curl_setopt must be used correctly to avoid silent failures
  • In Swift, the RunLoop.main.run() is necessary for async tasks in a CLI context
  • In Rust, the reqwest client must be awaited properly in async contexts
  • In C#, HttpClient should ideally be reused, not recreated per request

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 instead of hardcoding the API key?

Environment variables prevent accidental exposure of secrets in version control or logs. They also allow easy switching between different environments (dev, staging, prod).

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or chunked response handling. For example, in Python's requests, use `response.iter_content()`; in Go, use `io.Copy()` with a buffer.

Can I use a different HTTP client library?

Yes, but ensure it supports the same features (headers, auth, SSL). Popular alternatives include Python's httpx, Node's undici, or Go's fasthttp for performance-critical cases.

What if the API requires a custom timeout?

Most libraries allow setting timeouts. For example, in Python's requests: `requests.get(..., timeout=10)`; in Go: `http.Client{Timeout: 10 * time.Second}`.