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/teammates -H "Authorization: Bearer SG.12345678-1234-1234-1234-1234567890ab"

Python · requests

import os
import requests

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

Python · httpx

import os
import httpx

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

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://api.sendgrid.com/v3/teammates', {
  headers: {
    'Authorization': `Bearer ${process.env.SENDGRID_API_KEY}`
  }
});
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/teammates', {
  headers: {
    'Authorization': `Bearer ${process.env.SENDGRID_API_KEY}`
  }
});
console.log(response.data);

Go · net/http

package main

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

func main() {
	client := &http.Client{}
	req, err := http.NewRequest("GET", "https://api.sendgrid.com/v3/teammates", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("SENDGRID_API_KEY"))

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

	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("HTTP error! status: %d", resp.StatusCode))
	}

	// Handle response body as needed
}

PHP · cURL

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.sendgrid.com/v3/teammates');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SENDGRID_API_KEY')
]);

$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");
}
$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/teammates')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{ENV['SENDGRID_API_KEY']}"

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

unless res.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{res.code}"
end

puts JSON.parse(res.body)

Swift · URLSession

import Foundation

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

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 reqwest;
use std::error::Error;

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

    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).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();
        client.DefaultRequestHeaders.Add(
            "Authorization", 
            $"Bearer {Environment.GetEnvironmentVariable("SENDGRID_API_KEY")}"
        );

        var response = await client.GetAsync("https://api.sendgrid.com/v3/teammates");
        response.EnsureSuccessStatusCode();
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(content);
    }
}

Translation notes

  • All implementations use environment variables for the API key (SENDGRID_API_KEY)
  • Error handling is minimal but includes status code checks
  • Python and Node.js examples use async/await where applicable
  • Go and Rust examples use standard library HTTP clients
  • PHP example uses cURL for HTTP requests
  • Ruby example uses Net::HTTP for simplicity
  • Swift example uses URLSession with async/await pattern
  • C# example uses HttpClient with async/await

Common pitfalls when porting

  • Forgetting to set the SENDGRID_API_KEY environment variable before running
  • Not handling potential network errors (timeouts, DNS failures, etc.)
  • Assuming the response body is always JSON (may need content-type checks)
  • Ignoring HTTP status codes beyond success (2xx)
  • Hardcoding the API key in the code instead of using environment variables

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 for the API key?

Environment variables are a secure way to handle secrets. They prevent accidental exposure of sensitive data in code repositories or logs.

How do I handle pagination in the teammates endpoint?

The SendGrid API may return paginated results. Check the 'Link' header or 'meta' field in the response for pagination links.

What if I need to add query parameters?

Append them to the URL as key-value pairs. For example: 'https://api.sendgrid.com/v3/teammates?limit=10&offset=0'.

How do I handle rate limits?

Check the 'X-RateLimit-Remaining' header and implement exponential backoff if needed.