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=YOUR_API_KEY -H "Content-Type: application/json" -d '{"contents":[{"parts":[{"text":"Write a poem about AI"}]}]}'

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"}
data = {"contents": [{"parts": [{"text": "Write a poem about AI"}]}]}

response = requests.post(url, params=params, 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"
params = {"key": os.environ["GEMINI_API_KEY"]}
headers = {"Content-Type": "application/json"}
data = {"contents": [{"parts": [{"text": "Write a poem about AI"}]}]}

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

Node.js · fetch

const fetch = require('node-fetch');

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

const headers = {'Content-Type': 'application/json'};
const body = JSON.stringify({
  contents: [{ parts: [{ text: 'Write a poem about AI' }] }]
});

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

Node.js · axios

const axios = require('axios');

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

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

Go · net/http

package main

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

func main() {
	url := "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=" + os.Getenv("GEMINI_API_KEY")
	
	data := map[string]interface{}{
		"contents": []map[string]interface{}{
			{"parts": []map[string]interface{}{
				{"text": "Write a poem about AI"},
			}},
		},
	}
	
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	
	req.Header.Set("Content-Type", "application/json")
	
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}
	
	req.Body = io.NopCloser(bytes.NewBuffer(jsonData))
	
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()
	
	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Request failed with status: %s\n", resp.Status)
		return
	}
	
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}
	
	fmt.Println(string(body))
}

PHP · cURL

<?php
$url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=' . urlencode(getenv('GEMINI_API_KEY'));
$headers = ['Content-Type: application/json'];
$data = json_encode([
    'contents' => [[
        'parts' => [[
            'text' => 'Write a poem about AI'
        ]]
    ]]
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($ch);
if (curl_errno($ch)) {
    die('Error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    die("Request failed with status: $httpCode");
}

print_r(json_decode($response, true));
?>

Ruby · net/http

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

url = URI.parse("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent")
url.query = URI.encode_www_form({ key: ENV['GEMINI_API_KEY'] })

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

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

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

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let apiKey = ProcessInfo.processInfo.environment["GEMINI_API_KEY"] ?? ""
let url = URL(string: "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=@\(apiKey)")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

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

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

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("Request failed with status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}
task.resume()

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

Rust · reqwest

use std::env;
use reqwest::blocking;
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = env::var("GEMINI_API_KEY")?;
    let client = blocking::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 AI"
            }]
        }]
    });

    let response = client
        .post(&url)
        .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: serde_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 apiKey = Environment.GetEnvironmentVariable("GEMINI_API_KEY");
        var url = $"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={apiKey}";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var body = new
        {
            contents = new[]
            {
                new
                {
                    parts = new[]
                    {
                        new { text = "Write a poem about AI" }
                    }
                }
            }
        };

        var response = await client.PostAsJsonAsync(url, body);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Request failed with status: {response.StatusCode}");
            return;
        }

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

Translation notes

  • All implementations use environment variables for API keys (GEMINI_API_KEY)
  • Python implementations use both requests and httpx for variety
  • Go implementation uses standard library only (no third-party HTTP clients)
  • Swift uses URLSession for async networking
  • Rust uses reqwest blocking client for simplicity
  • C# uses HttpClient with PostAsJsonAsync helper
  • Error handling checks HTTP status codes and raises exceptions where idiomatic
  • JSON bodies are constructed as objects/dicts, not raw strings

Common pitfalls when porting

  • Forgetting to set the Content-Type header in Go or Ruby may cause the server to reject the request
  • In Swift, the async task must be allowed to complete (e.g., by running the main run loop)
  • In Rust, blocking clients may not be suitable for production async applications
  • In PHP, ensure curl is installed and enabled in php.ini
  • In Node.js, using fetch requires Node.js 18+ or a polyfill
  • In Python, httpx requires Python 3.7+ and may need to be installed via pip

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 API keys instead of hardcoding?

Environment variables prevent API keys from being committed to version control, reducing the risk of exposure. They also allow different configurations across development, testing, and production environments.

Can I use async/await in Python with requests?

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

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

The examples focus on a single request. For pagination or streaming, you would need to extend the code to handle multiple requests or use streaming APIs provided by the libraries (e.g., httpx.AsyncClient.stream() or reqwest's streaming).

Why does the Go example use a blocking HTTP client?

The Go example uses the standard library's blocking client for simplicity. In production Go code, you might use a more advanced HTTP client like fasthttp or implement async patterns with goroutines.