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 GET https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent \
  -H "Authorization: Bearer AIzaSyD1234567890abcdefghijklmnopqrstuvwx" \
  -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"
headers = {
    "Authorization": f"Bearer {os.environ['GEMINI_API_KEY']}",
    "Content-Type": "application/json"
}
data = {
    "contents": [{"parts": [{"text": "Write a poem about AI."}]}]
}

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": "Write a poem about AI."}]}]
}

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

Node.js · fetch

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

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: 'Write a poem about AI.' }] }]
};

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

const axios = require('axios');

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: 'Write a poem about AI.' }] }]
};

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

Go · net/http

package main

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

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

type ResponseBody struct {
	Candidates []interface{} `json:"candidates"`
}

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: "Write a poem about AI."},
				},
			},
		},
	}

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

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	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 {
		log.Fatalf("Request failed with status: %s", resp.Status)
	}

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	var result ResponseBody
	if err := json.Unmarshal(respBody, &result); err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(respBody))
}

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');
}

$data = [
    'contents' => [
        ['parts' => [
            ['text' => 'Write a poem about AI.']
        ]]
    ]
];

$options = [
    'http' => [
        'header'  => [
            "Authorization: Bearer $apiKey",
            "Content-Type: application/json"
        ],
        'method'  => 'POST',
        'content' => json_encode($data),
        'ignore_errors' => true
    ]
];

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

if ($result === FALSE) {
    die('Request failed');
}

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

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['GEMINI_API_KEY']
raise 'GEMINI_API_KEY environment variable not set' unless api_key

request_body = {
  contents: [{
    parts: [{
      text: 'Write a poem about AI.'
    }]
  }]
}

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

request = Net::HTTP::Post.new(url.request_uri, {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json'
})
request.body = request_body.to_json

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP request failed: #{response.code} #{response.message}"
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 requestBody: [String: Any] = [
    "contents": [
        ["parts": [
            ["text": "Write a poem about AI."]
        ]]
    ]
]

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
} 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 code: \((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 std::env;
use reqwest::blocking::Client;
use serde_json::json;

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 response = client
        .post(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .header("Content-Type", "application/json")
        .json(&json!({
            "contents": [{"parts": [{"text": "Write a poem about AI."}]}]
        }))
        .send()?;

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

    let body = response.text()?;
    println!("{}", body);
    Ok(())
}

C# · HttpClient

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main(string[] args)
    {
        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 requestBody = new
        {
            contents = new[]
            {
                new
                {
                    parts = new[]
                    {
                        new { text = "Write a poem about AI." }
                    }
                }
            }
        };

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

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

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), System.Text.Encoding.UTF8, "application/json");
        return await httpClient.PostAsync(url, content);
    }
}

Translation notes

  • All implementations use environment variables for secrets (GEMINI_API_KEY)
  • Python requests and httpx use .json() for automatic serialization
  • Go requires manual JSON struct definitions
  • PHP uses stream context for simplicity
  • Ruby uses Net::HTTP with JSON serialization
  • Swift uses URLSession with async task
  • Rust uses reqwest blocking client for simplicity
  • C# uses HttpClient with extension method for JSON serialization

Common pitfalls when porting

  • Forgetting to set GEMINI_API_KEY environment variable
  • Using GET instead of POST (the endpoint requires POST)
  • Not handling HTTP errors properly
  • Manually stringifying JSON bodies instead of using library helpers
  • Ignoring SSL/TLS verification in Go or other low-level clients

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 method POST when the cURL uses -X GET?

The Google Generative AI API endpoint requires a POST request despite the cURL command using -X GET. The actual method is determined by the API specification, not the cURL flag.

Can I use a different HTTP client library?

Yes, but ensure it supports automatic JSON serialization, proper error handling, and environment variable integration for secrets.

How do I install the required dependencies?

For Python: `pip install requests httpx`; Node.js: `npm install axios node-fetch`; Go: `go get github.com/valyala/fasthttp` or use standard library; PHP: built-in; Ruby: built-in; Swift: built-in; Rust: `cargo add reqwest serde_json`; C#: built-in with .NET 6+