Qaynaq LABS · TOOLS

CURL → CODE · POST · API-KEY

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?key=AIza1234567890abcdef \
  --header "Content-Type: application/json" \
  --data '{"contents":[{"parts":[{"text":"Write a poem about the ocean"}]}]}'

Python · requests

import os
import requests

url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent"
params = {"key": os.environ["GEMINI_API_KEY"]}
headers = {"Content-Type": "application/json"}
body = {"contents": [{"parts": [{"text": "Write a poem about the ocean"}]}]}

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

Python · httpx

import os
import httpx

url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent"
params = {"key": os.environ["GEMINI_API_KEY"]}
headers = {"Content-Type": "application/json"}
body = {"contents": [{"parts": [{"text": "Write a poem about the ocean"}]}]}

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

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'process';

const url = new URL('https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent');
url.searchParams.set('key', env.GEMINI_API_KEY);

const response = await fetch(url, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    contents: [{ parts: [{ text: 'Write a poem about the ocean' }] }]
  })
});

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';
import { env } from 'process';

const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';
const params = { key: env.GEMINI_API_KEY };
const headers = { 'Content-Type': 'application/json' };
const body = { contents: [{ parts: [{ text: 'Write a poem about the ocean' }] }] };

try {
  const response = await axios.post(url, body, { params, headers });
  console.log(response.data);
} catch (error) {
  if (error.response) {
    console.error(`HTTP error! status: ${error.response.status}`);
  } else {
    console.error('Error:', error.message);
  }
}

Go · net/http

package main

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

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

type ResponseBody struct {
	Candidates []struct {
		Content struct {
			Parts []struct {
				Text string `json:"text"`
			} `json:"parts"`
		} `json:"content"`
	} `json:"candidates"`
}

func main() {
	apiKey := os.Getenv("GEMINI_API_KEY")
	if apiKey == "" {
		log.Fatal("GEMINI_API_KEY environment variable not set")
	}

	url := "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=" + apiKey
	body := RequestBody{
		Contents: []struct {
			Parts []struct {
				Text string `json:"text"`
			} `json:"parts"`
		}{
			{
				Parts: []struct {
					Text string `json:"text"`
				}{
					{Text: "Write a poem about the ocean"},
				},
			},
		},
	}

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

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonBody))
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("HTTP error! status: %s, body: %s", resp.Status, body)
	}

	var result ResponseBody
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	fmt.Println(result)
}

PHP · cURL

<?php
$apiKey = getenv('GEMINI_API_KEY');
if (empty($apiKey)) {
    die('GEMINI_API_KEY environment variable not set');
}

$url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . urlencode($apiKey);
$body = json_encode([
    'contents' => [
        ['parts' => [
            ['text' => 'Write a poem about the ocean']
        ]]
    ]
]);

$options = [
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\n",
        'content' => $body
    ]
];

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

if ($response === false) {
    die('Request failed');
}

$httpResponse = $http_response_header;
if (strpos($httpResponse[0], 'HTTP/') === 0 && strpos($httpResponse[0], '200') === false) {
    die('HTTP error! status: ' . $httpResponse[0]);
}

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

Ruby · net/http

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

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

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

request = Net::HTTP::Post.new(url.request_uri, 'Content-Type' => 'application/json')
request.body = {
  contents: [{
    parts: [{
      text: 'Write a poem about the ocean'
    }]
  }]
}.to_json

response = http.request(request)

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

guard let apiKey = ProcessInfo.processInfo.environment["GEMINI_API_KEY"] else {
    fatalError("GEMINI_API_KEY environment variable not set")
}

let url = URL(string: "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=API_KEY_PLACEHOLDER")!
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
components.queryItems = [URLQueryItem(name: "key", value: apiKey)]

var request = URLRequest(url: components.url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let body: [String: Any] = [
    "contents": [
        ["parts": [
            ["text": "Write a poem about the ocean"]
        ]]
    ]
]

request.httpBody = try JSONSerialization.data(withJSONObject: body)

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

    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }

    guard (200...299).contains(httpResponse.statusCode) else {
        fatalError("HTTP error! status: \(httpResponse.statusCode)")
    }

    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 serde_json::json;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = env::var("GEMINI_API_KEY")?;

    let client = reqwest::Client::new();
    let url = format!(
        "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={}",
        api_key
    );

    let body = json!({
        "contents": [{
            "parts": [{
                "text": "Write a poem about the ocean"
            }]
        }]
    });

    let response = client
        .post(&url)
        .json(&body)
        .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 json: serde_json::Value = response.json().await?;
    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 apiKey = Environment.GetEnvironmentVariable("GEMINI_API_KEY");
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.Error.WriteLine("GEMINI_API_KEY environment variable not set");
            return;
        }

        var url = $"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={apiKey}";
        var body = new
        {
            contents = new[]
            {
                new
                {
                    parts = new[]
                    {
                        new { text = "Write a poem about the ocean" }
                    }
                }
            }
        };

        using var client = new HttpClient();
        var content = new StringContent(JsonSerializer.Serialize(body));
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.PostAsync(url, content);
        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.Error.WriteLine($"HTTP error! status: {response.StatusCode}, body: {errorContent}");
            return;
        }

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

Translation notes

  • All implementations read the API key from an environment variable named GEMINI_API_KEY
  • Python requests and httpx use the json parameter for automatic serialization
  • Go uses structs for type-safe request/response handling
  • Swift uses URLComponents to safely construct the query string
  • Rust uses tokio for async runtime and reqwest for HTTP client
  • C# uses System.Text.Json for JSON serialization
  • Error handling checks HTTP status codes and raises exceptions where appropriate

Common pitfalls when porting

  • Forgetting to set the GEMINI_API_KEY environment variable will cause failures
  • In Go, not properly closing the response body can lead to resource leaks
  • In Swift, the RunLoop.main.run() is required for async tasks in a command-line context
  • In Rust, missing the tokio runtime will cause compilation errors
  • In PHP, not properly handling HTTP errors can lead to silent failures
  • In Node.js, forgetting to await async operations will cause unhandled promise rejections

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 don't expose secrets in source code or version control systems. They also allow for different configurations across environments (development, staging, production).

How do I handle pagination or streaming responses in these implementations?

The current implementations are for a single request. For pagination, you would need to inspect the response for next page tokens and make subsequent requests. For streaming, you would use libraries that support server-sent events or WebSockets depending on the API's capabilities.