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/scopes \
  -H "Authorization: Bearer SG.abc123.def456" \
  -H "Content-Type: application/json"

Python · requests

import os
import requests

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

Python · httpx

import os
import httpx

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

Node.js · fetch

import fetch from 'node-fetch';

const response = await fetch('https://api.sendgrid.com/v3/scopes', {
  headers: {
    'Authorization': `Bearer ${process.env.SENDGRID_API_KEY}`,
    'Content-Type': 'application/json'
  }
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

Node.js · axios

import axios from 'axios';

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

Go · net/http

package main

import (
	"net/http"
	"os"
)

func main() {
	req, err := http.NewRequest("GET", "https://api.sendgrid.com/v3/scopes", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("SENDGRID_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		panic("Request failed")
	}
}

PHP · cURL

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.sendgrid.com/v3/scopes');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . getenv('SENDGRID_API_KEY'),
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
    throw new Exception('Request failed');
}
curl_close($ch);
?>

Ruby · net/http

require 'net/http'
require 'json'

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

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end
raise "Request failed" unless res.is_a?(Net::HTTPSuccess)

Swift · URLSession

import Foundation

let url = URL(string: "https://api.sendgrid.com/v3/scopes")!
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 httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        fatalError("Request failed")
    }
    // Process data here
}
task.resume()

Rust · reqwest

use reqwest;
use std::env;

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

    assert!(response.status().is_success());
    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")}");
        client.DefaultRequestHeaders.Add("Content-Type", "application/json");

        var response = await client.GetAsync("https://api.sendgrid.com/v3/scopes");
        response.EnsureSuccessStatusCode();
    }
}

Translation notes

  • All implementations use environment variables for the API key (SENDGRID_API_KEY).
  • Error handling is minimal but includes status code checks.
  • Headers are preserved exactly as in the cURL command.
  • No request body is sent (GET method).

Common pitfalls when porting

  • Forgetting to set the SENDGRID_API_KEY environment variable before running the code.
  • In Go, not closing the response body can lead to resource leaks.
  • In Swift, the URLSession task must be started with `resume()`.
  • In Rust, the `reqwest` client must be awaited in an async context.
  • In PHP, `curl_setopt` must include `CURLOPT_RETURNTRANSFER` to capture the response.

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 for different configurations across 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`, you can iterate over the response content in chunks.

Can I use a different HTTP client library?

Yes, but ensure it supports the same features (headers, auth, SSL) as the standard library. Popular alternatives include `httpx` in Python or `fetch` in Node.js.