Google Gemini API: Setup and Usage
Google Gemini is a powerful multimodal AI model from Google DeepMind. Gemini 1.5 Pro supports a context window of up to 1 million tokens — more than any other commercial API. Gemini 1.5 Flash is fast and free for small workloads.
Getting an API Key
Go to aistudio.google.com, create a project, and get an API key. Free tier: 15 RPM (requests per minute) and 1,500,000 tokens/day for Gemini 1.5 Flash.
Your First Request
pip install google-generativeai import google.generativeai as genai
import os
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
model = genai.GenerativeModel("gemini-1.5-flash")
response = model.generate_content("Explain how VPS hosting works in 3 sentences.")
print(response.text) Multi-Turn Chat
chat = model.start_chat(history=[])
response1 = chat.send_message("I am setting up nginx on Ubuntu.")
print(response1.text)
response2 = chat.send_message("How do I add an SSL certificate?")
print(response2.text) # remembers the context of previous messages Image Analysis (Vision)
import google.generativeai as genai
from PIL import Image
model = genai.GenerativeModel("gemini-1.5-flash")
image = Image.open("server-screenshot.png")
response = model.generate_content([
"Describe what is shown and find any possible problems:",
image
])
print(response.text) PHP Integration (via REST API)
<?php
function askGemini(string $prompt): string {
$apiKey = $_ENV['GEMINI_API_KEY'];
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={$apiKey}";
$data = [
'contents' => [['parts' => [['text' => $prompt]]]]
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($data),
]);
$r = json_decode(curl_exec($ch), true);
curl_close($ch);
return $r['candidates'][0]['content']['parts'][0]['text'] ?? '';
}
echo askGemini('Write a short description for a hosting page'); Gemini Pricing (2025)
| Model | Input (1M) | Output (1M) | Context |
|---|---|---|---|
| Gemini 1.5 Flash | $0.075 | $0.30 | 1M tokens |
| Gemini 1.5 Pro | $3.50 | $10.50 | 1M tokens |
| Gemini 2.0 Flash | $0.10 | $0.40 | 1M tokens |
Common Errors
Gemini API errors usually point to a specific, easily fixable cause, as long as you do not ignore the text in the response's message field.
400 — API Key Not Valid. Please Pass a Valid API Key
The key was copied with a typo, revoked in aistudio.google.com, or belongs to a different Google Cloud project than the one it is being used from. Recreate the key and make sure the environment variable is read without extra spaces or line breaks.
429 — Resource Has Been Exhausted (e.g. Check Quota)
You exceeded the requests-per-minute limit or the daily token quota for the selected model. Unlike a temporary server overload, this error will not clear itself within seconds — you either need to slow down the request rate or move to a paid tier with higher limits.
Free Tier vs Paid Tier: What to Watch
| Parameter | Free tier | Paid tier |
|---|---|---|
| Requests-per-minute limit | Limited, depends on the model | Noticeably higher |
| Daily token quota | Fixed, one shared quota per day | Effectively removed, billed by actual usage |
| Data used for training | May be used, see the service terms | Usually excluded under paid-tier terms |
| Good for | Prototypes, testing, small load | Production with predictable traffic |
When the Gemini API Is Not a Good Fit
- Data privacy is critical and data cannot leave your own infrastructure — a local option such as Ollama is needed then.
- The product is already tied to the OpenAI ecosystem (assistants, tools, the function-calling format) — migrating the request and response format requires a separate compatibility layer.
- You need a stable price with no surprises as load grows — Gemini's free tier is built for small volumes and is not a solid base for a production service.
- You need a guaranteed response latency — like other cloud APIs, response time is not guaranteed during the provider's peak load.
Verifying the Key and Requests Work
curl -s "https://generativelanguage.googleapis.com/v1beta/models?key=$GEMINI_API_KEY" | head -c 200 A successful response is JSON with the list of available models. If a 400 error about an invalid key comes back, the problem is at the key level, and it is too early to debug chat or image analysis logic.
Frequently asked questions
Do you need to buy a key for the Gemini API, or is it issued for free?
A Gemini API key is never purchased separately — it is created free of charge in Google AI Studio right after setting up a project, and billing only starts once usage goes beyond the free limits rather than for the key itself. Any Google account holder gets access instantly, with no support ticket or upfront license agreement required.
Is the free tier good enough for a production project with real traffic?
The free tier suits testing and small prototypes: request and token limits are fixed and identical for everyone, and response latency during peak hours is not guaranteed. A service with steady traffic and predictable response time should move to the paid tier ahead of time, or the application may suddenly hit a limit at the worst moment.
Does Google use data sent through the Gemini API to train its models?
Whether data gets used for training is described in the service terms and depends on the tier chosen, not on one fixed rule for everyone. On the free tier, request data can end up feeding model training, while the paid plan usually excludes that. Check the current terms for your exact API version before sending sensitive information.
Which Gemini model should a project use, Flash or Pro?
Flash is a fast, inexpensive model suited to routine tasks such as chatbots, short answers, and simple image analysis, while Pro handles complex reasoning and very long conversation context better. For most hosting projects it makes sense to start with Flash and switch to Pro only once answer quality turns out clearly insufficient for the task at hand.