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/asm/groups \
  -H "Authorization: Bearer SG.1234567890abcdefghijklmnopqrstuvwx" \
  -H "Content-Type: application/json"

Python · requests

import os
import requests

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

Python · httpx

import os
import httpx

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

Node.js · fetch

import fetch from 'node-fetch';

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

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

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

Node.js · axios

import axios from 'axios';

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

console.log(response.data);

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/asm/groups", 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("HTTP error! status: %s, body: %s", resp.Status, 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/asm/groups');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SENDGRID_API_KEY'),
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    throw new Exception('Curl error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    throw new Exception("HTTP error! status: $httpCode, body: $response");
}

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

curl_close($ch);

Ruby · net/http

require 'net/http'
require 'json'

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

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

response = http.request(req)
unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{response.code}, body: #{response.body}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.sendgrid.com/v3/asm/groups")!
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
    if let error = error {
        fatalError("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    if let data = data, 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;

#[tokio::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/asm/groups")
        .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!("HTTP error! status: {}, body: {}", 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 apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
        client.DefaultRequestHeaders.Add("Content-Type", "application/json");

        var response = await client.GetAsync("https://api.sendgrid.com/v3/asm/groups");
        if (!response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            throw new Exception($"HTTP error! status: {response.StatusCode}, body: {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 and reads response body on failure
  • JSON responses are parsed into native data structures where applicable
  • Go and Rust require async/await for HTTP calls
  • Swift uses URLSession for networking

Common pitfalls when porting

  • Forgetting to set the environment variable SENDGRID_API_KEY before running the code
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • In Go, not closing the response body can lead to resource leaks
  • In Rust, forgetting to enable the 'tokio' runtime feature in Cargo.toml
  • In Swift, not running the task in a run loop can cause the program to exit prematurely

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 are more secure as they avoid exposing secrets in source code or version control. They also allow for easy configuration changes without modifying the code.

How do I set the SENDGRID_API_KEY environment variable?

For local development, set it in your shell (e.g., `export SENDGRID_API_KEY='your_key'` on Unix-like systems). In production, use your deployment platform's secrets management (e.g., Kubernetes secrets, AWS Secrets Manager).

Why does the Swift example use RunLoop.main.run()?

Swift's URLSession tasks are asynchronous. Without a run loop, the program would exit before the network request completes. RunLoop.main.run() keeps the program alive to handle the response.

Can I use a different HTTP client library in these languages?

Yes, but the provided examples use the most idiomatic and widely-used libraries for each language. Alternatives may require additional setup or have different trade-offs.