GCP

Step-by-Step Guide to Using Google AI Gemini API with CURL

CK CK 3788 
Created at  
3,210 0 0

I want to figure out if Gemini can accept a larger prompt longer than 4000 bytes, because many AI foundation models have restrictions, and it looks like Gemini seems to have better coverage, fortunately.

 

1. Get an API Key

You need an API key to authenticate your requests.

  • Go to Google AI Studio.
  • In the left navigation, click on "Get API key" (or similar, it might be under a menu or directly visible).
  • Create a new API key.
  • Important: Treat your API key like a password. Do not expose it in public repositories or client-side code. For development, you can use it directly, but for production, consider more secure methods like environment variables or server-side calls.

 

2. Choose Your Model and Endpoint

The most common models are:

  • gemini-pro: For text-only input and output.
  • gemini-pro-vision: For multimodal input (text and images).

The primary endpoint for generating content is generateContent.

  • URL Base: https://generativelanguage.googleapis.com/v1beta/
  • Endpoint for Gemini Pro: models/gemini-pro:generateContent

 

3. Construct Your CURL Request (Example for gemini-pro)

Here's a basic CURL command to send a text prompt to the gemini-pro model:

curl -X POST \
  -H "Content-Type: application/json" \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Tell me a short story about a brave knight."
          }
        ]
      }
    ]
  }'

 

Let's break down each part:

  • curl: The command-line tool.
  • -X POST: Specifies the HTTP method as POST, which is required for generateContent.
  • -H "Content-Type: application/json": Sets the Content-Type header, indicating that your request body is in JSON format.
  • "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY":
    • This is the full URL to the API endpoint.
    • YOUR_API_KEY: Replace this placeholder with the actual API key you generated.
  • -d '{ ... }': Specifies the request body data.
    • "contents": An array of content blocks. For simple text prompts, you'll usually have one block.
    • "parts": An array within each content block, describing the individual parts of the prompt.
    • "text": "...": The actual text of your prompt.

 

4. Example for gemini-pro-vision (Multimodal)

For gemini-pro-vision, you'd include image data. This is typically done by providing a base64 encoded string of the image.

# First, you'd base64 encode your image.
Example (macOS/Linux, replace image.jpg with your image file):
base64_image_data=$(base64 -i image.jpg | tr -d '\n')
Then use it in the curl command:curl -X POST \
  -H "Content-Type: application/json" \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=YOUR_API_KEY" \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "What is in this image?"
          },
          {
            "inlineData": {
              "mimeType": "image/jpeg",
              "data": "YOUR_BASE64_ENCODED_IMAGE_DATA_HERE"
            }
          }
        ]
      }
    ]
  }'

Note: Replacing YOUR_BASE64_ENCODED_IMAGE_DATA_HERE can make the CURL command very long. For practical use, you'd usually prepare this data in a script or program.

 

5. Expected Response

The API will return a JSON object, typically containing the generated text in candidates[0].content.parts[0].text.

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "In a land shrouded in mist and ancient lore, Sir Alaric, a knight of unwavering courage, stood guard over the kingdom of Eldoria..."
          }
        ]
      },
      "finishReason": "STOP",
      "index": 0,
      "safetyRatings": []
    }
  ]
}

 

The Google Gemini API allows you to interact with various Gemini models (gemini-pro, gemini-pro-vision, embedding-001) to perform tasks like text generation, multi-modal input (text + image), and text embeddings.

You'll make API calls using curl on your terminal.

 

 

6. Multi-turn Conversation (Chat) with gemini-pro

To maintain context in a conversation, you need to send the entire history of turns (user and model) with each new request.

Model: gemini-pro
Endpoint: :generateContent

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Hello, how are you?"}]},
      {"role": "model", "parts": [{"text": "I am doing well, thank you! How can I assist you today?"}]},
      {"role": "user", "parts": [{"text": "What is the capital of France?"}]}
    ]
  }'

 

Explanation:

  • Each object in the contents array represents a turn.
  • role: Specifies who is speaking (user or model).
  • The last user turn is the current prompt.

 

7. Multi-modal Input (Image + Text) with gemini-pro-vision

This allows you to send both an image and text in a single prompt. The image data must be Base64 encoded.

Model: gemini-pro-vision
Endpoint: :generateContent

Steps:
1. Prepare an image file (e.g., my_image.jpg).
2. Base64 encode the image. On Linux/macOS, you can use:
 

    BASE64_IMAGE_DATA=$(base64 -w 0 my_image.jpg)
    echo $BASE64_IMAGE_DATA
    

(Note: -w 0 prevents line wrapping, which is important for cURL.)
3. Replace YOUR_BASE64_ENCODED_IMAGE in the cURL command with the output from the previous step.

 

# --- FIRST, BASE64 ENCODE YOUR IMAGE (e.g., my_image.jpg) ---
For Linux/macOS:
BASE64_IMAGE_DATA=$(base64 -w 0 my_image.jpg)
For Windows (PowerShell):
$BASE64_IMAGE_DATA=[Convert]::ToBase64String([System.IO.File]::ReadAllBytes("my_image.jpg"))
echo $BASE64_IMAGE_DATA--- THEN, RUN THE CURL COMMAND ---
curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          {"text": "What is in this picture? Provide a detailed description."},
          {
            "inline_data": {
              "mime_type": "image/jpeg",
              "data": "YOUR_BASE64_ENCODED_IMAGE"
            }
          }
        ]
      }
    ]
  }'

 

Explanation:

  • gemini-pro-vision: The specific model for multi-modal input.
  • inline_data: Used for sending non-text data directly within the request.
  • mime_type: Specifies the type of the image (e.g., image/jpeg, image/png).
  • data: Your Base64-encoded image string.

Important: Image sizes are limited (e.g., 4MB per image for gemini-pro-vision).

 

8. Text Embeddings with embedding-001

Embeddings convert text into a dense vector representation, useful for similarity search, clustering, etc.

Model: embedding-001
Endpoint: :embedContent

 

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/embedding-001:embedContent?key=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": {
      "parts": [
        {"text": "The quick brown fox jumps over the lazy dog."}
      ]
    }
  }'

 

Explanation:

  • content: Note it's singular content for embeddings, not contents.
  • The response will contain a values array with floating-point numbers representing the embedding vector.

Example Response (truncated):
 

{
  "embedding": {
    "values": [
      0.009088515,
      -0.015039304,
      -0.0076045576,
      ...,
      0.012345678
    ]
  }
}

 

9. Including generationConfig (Optional)

You can customize generation parameters like temperature, topK, topP, and maxOutputTokens. These are top-level fields in the request body, not inside parts.

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 short, creative story about a talking teacup."}
        ]
      }
    ],
    "generationConfig": {
      "temperature": 0.9,
      "topK": 40,
      "topP": 0.95,
      "maxOutputTokens": 200
    }
  }'

 

Important Notes:

  • API Key Security: Never hardcode your API key in production code. Use environment variables or a secure configuration management system.
  • Error Handling: Check the curl output for HTTP status codes (e.g., 400 for bad request, 401 for unauthorized, 403 for forbidden, 500 for server errors).
  • JSON Formatting: Be very careful with JSON syntax in cURL. Missing commas, brackets, or incorrect quotes can cause errors. Using \ for line continuation makes it more readable but also prone to errors if not used correctly.
  • Model Versioning: v1beta is often used for pre-release features. Check the official Google documentation for the latest recommended stable versions if you're building a production application.
  • Safety Settings: The Gemini API has built-in safety features. Responses may be blocked if they violate safety policies. You can also configure safetySettings in your request if needed, similar to generationConfig.
Tags Gemini API Google AI Studio gemini-pro gemini-pro-vision Facebook X
Comments 0
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Creating a Service Account via Google Cloud Console (UI)
    1,068
  3. Improving nested_fields data access experience with a persistent user-defined function (aka UDF) in Google Big Query
    1,505
  4. Creating a query based on record type data field in Google BigQuery
    1,642
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  3. How do I create animated background for Google Meet?
    23,252
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  7. Array of arguments passed to script in PHP
    99
  8. Invalid Auction Storms in Ad Tech
    107
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  10. The Two Clocks of Ad Server Architecture
    78
  11. Frequency Cap Architecture Overview
    527
  12. Collecting Proof-of-Play from 100,000 Screens
    153
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  14. What is RedisVL?
    117
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  16. TPU & GPU Cluster Management Tools
    258
  17. The Concept of Scaffolding in AI Agents
    245
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  22. Machine Learning: Training vs. Ranking
    230
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  25. Designing a Data Curation System Around a Vector Database
    230
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233
  30. Understanding Data Lineage
    272