Qaynaq LABS · TOOLS

CURL → CODE · POST · BEARER

cURL → 10 languages

POST generativelanguage.googleapis.com · body: json · secrets replaced with env vars.

Source cURL
curl -X POST https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent -H "Authorization: Bearer AIzaSyA1234567890abcdef" -H "Content-Type: application/json" -d '{"contents":[{"parts":[{"text":"Hello!"}]}]}'

Python · requests

import os
import requests

url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent"
headers = {
    "Authorization": f"Bearer {os.environ['GEMINI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "contents": [{"parts": [{"text": "Hello!"}]}]
}

response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent"
headers = {
    "Authorization": f"Bearer {os.environ['GEMINI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "contents": [{"parts": [{"text": "Hello!"}]}]
}

with httpx.Client() as client:
    response = client.post(url, headers=headers, json=data)
    response.raise_for_status()
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { config } from 'dotenv';

config();

const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';
const headers = {
  'Authorization': `Bearer ${process.env.GEMINI_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  contents: [{ parts: [{ text: 'Hello!' }] }]
};

fetch(url, {
  method: 'POST',
  headers,
  body: JSON.stringify(data)
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';
import { config } from 'dotenv';

config();

const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';
const headers = {
  'Authorization': `Bearer ${process.env.GEMINI_API_KEY}`,
  'Content-Type': 'application/json'
};
const data = {
  contents: [{ parts: [{ text: 'Hello!' }] }]
};

axios.post(url, data, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

Go · net/http

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

type RequestBody struct {
	Contents []struct {
		Parts []struct {
			Text string `json:"text"`
		} `json:"parts"`
	} `json:"contents"`
}

func main() {
	url := "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent"
	apiKey := os.Getenv("GEMINI_API_KEY")
	if apiKey == "" {
		log.Fatal("GEMINI_API_KEY environment variable not set")
	}

	body := RequestBody{
		Contents: []struct {
			Parts []struct {
				Text string `json:"text"`
			} `json:"parts"`
		}{
			{
				Parts: []struct {
					Text string `json:"text"`
				}{
					{Text: "Hello!"},
				},
			},
		},
	}

	jsonData, err := json.Marshal(body)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+apiKey)
	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 != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Request failed with status %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 · cURL

<?php

$url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';
$apiKey = getenv('GEMINI_API_KEY');
if (empty($apiKey)) {
    die('GEMINI_API_KEY environment variable not set');
}

$headers = [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
];

$data = [
    'contents' => [
        ['parts' => [
            ['text' => 'Hello!']
        ]]
    ]
];

$options = [
    'http' => [
        'header' => $headers,
        'method' => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    die('Request failed: ' . $response);
}

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

Ruby · net/http

require 'net/http'
require 'json'
require 'uri'

url = URI.parse('https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent')
api_key = ENV.fetch('GEMINI_API_KEY')

headers = {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json'
}

data = {
  contents: [{
    parts: [{
      text: 'Hello!'
    }]
  }]
}

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

request = Net::HTTP::Post.new(url.path, headers)
request.body = data.to_json

response = http.request(request)

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let url = URL(string: "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let apiKey = ProcessInfo.processInfo.environment["GEMINI_API_KEY"] ?? ""
if apiKey.isEmpty {
    fatalError("GEMINI_API_KEY environment variable not set")
}

request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "contents": [
        ["parts": [
            ["text": "Hello!"]
        ]]
    ]
]

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: body)
} catch {
    fatalError("Failed to serialize request body: \(error)")
}

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        fatalError("Request failed: \(error)")
    }

    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
        fatalError("Request failed with status \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }

    guard let data = data else {
        fatalError("No data received")
    }

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
            print(json)
        }
    } catch {
        fatalError("Failed to parse response: \(error)")
    }
}

task.resume()

// Keep the program running to allow the async task to complete
RunLoop.main.run()

Rust · reqwest

use reqwest::blocking::Client;
use serde_json::{json, Value};
use std::env;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent";
    let api_key = env::var("GEMINI_API_KEY")?;

    let client = Client::new();
    let body = json!({
        "contents": [{
            "parts": [{
                "text": "Hello!"
            }]
        }]
    });

    let response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&body)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed with status: {}", response.status()).into());
    }

    let json: Value = response.json()?;
    println!("{}", json);

    Ok(())
}

C# · HttpClient

using System;
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://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent";
        var apiKey = Environment.GetEnvironmentVariable("GEMINI_API_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("GEMINI_API_KEY environment variable not set");
            return;
        }

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var body = new
        {
            contents = new[]
            {
                new
                {
                    parts = new[]
                    {
                        new { text = "Hello!" }
                    }
                }
            }
        };

        var response = await client.PostAsJsonAsync(url, body);
        response.EnsureSuccessStatusCode();

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

public static class HttpClientExtensions
{
    public static async Task<HttpResponseMessage> PostAsJsonAsync<T>(
        this HttpClient httpClient, string url, T data)
    {
        var content = new StringContent(JsonSerializer.Serialize(data));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        return await httpClient.PostAsync(url, content);
    }
}

Translation notes

  • All implementations use the idiomatic HTTP client for each language.
  • Bearer token is read from an environment variable named GEMINI_API_KEY to avoid hardcoding secrets.
  • Error handling includes status code checks and basic error reporting.
  • JSON bodies are constructed as objects/dictionaries, not raw strings.
  • Asynchronous operations are used where idiomatic (e.g., async/await in C#, Swift, Node.js).
  • Blocking HTTP clients are used in Go and Python requests for simplicity in examples.

Common pitfalls when porting

  • Forgetting to set the GEMINI_API_KEY environment variable before running the code.
  • Not handling HTTP errors properly (e.g., ignoring status codes or not reading the response body on failure).
  • In Rust, using the blocking client in a non-blocking context may cause issues; prefer async in production.
  • In Swift, forgetting to call RunLoop.main.run() will cause the async task to not complete.
  • In PHP, using file_get_contents with stream contexts may not be suitable for complex error handling in production.
  • In Go, not properly closing the response body can lead to resource leaks.

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 is the bearer token read from an environment variable instead of being hardcoded?

Hardcoding secrets like API keys in source code is a security risk. Environment variables allow secrets to be managed separately from the codebase, following the principle of least privilege.

How do I install the required dependencies for each language?

Each language has its own package manager: Python (pip install requests httpx), Node.js (npm install axios node-fetch), Go (go get), PHP (composer), Ruby (gem install), Swift (Swift Package Manager), Rust (cargo add reqwest serde_json), C# (NuGet packages).

Can I use async/await in Python requests?

No, the requests library is synchronous. For async HTTP in Python, use httpx or aiohttp instead.