Gemini API Quickstart — Getting Started with Python and TypeScript
Getting your first Gemini response back takes minutes — the only real decisions are where to grab an API key and which SDK to install. The friction shows up later, once you start layering in streaming and error handling.
We'll go from key, to first request, to something you'd actually ship, in both Python and TypeScript/JavaScript.
Prerequisites
Before you start, you'll need:
- A Google account
- Python 3.7+ (for Python projects) or Node.js 14+ (for TypeScript)
- pip or npm package manager
- An API key from Google AI Studio
Getting Your API Key
- Visit aistudio.google.com
- Click on "API key" in the left sidebar
- Select "Create API key"
- Choose "Create API key in new project" or use an existing project
- Copy your API key immediately—you'll only see it once
- Store it securely in your environment
Never hardcode API keys in your source code. Use environment variables instead:
export GEMINI_API_KEY="your-api-key-here"Python Quickstart
Installation
Install the Google AI Python SDK:
pip install google-genaiBasic Text Generation
Create your first program:
import os
from google import genai
# Initialize the client (reads GEMINI_API_KEY from environment)
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Simple text generation
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="Explain quantum computing in simple terms"
)
print(response.text)Understanding the Response
The response object contains:
# Full text content
print(response.text)
# Stop reason (why the model stopped generating)
print(response.stop_reason) # "STOP", "MAX_TOKENS", etc.
# Usage metrics
print(response.usage_metadata)
# {
# "prompt_tokens": 15,
# "candidates_tokens": 150,
# "total_tokens": 165
# }Multi-Turn Conversations
Build interactive conversations:
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Start a new chat session
chat = client.chats.create(model="gemini-2.5-pro")
# First turn
response1 = chat.send_message("What is machine learning?")
print(response1.text)
# Second turn (context is maintained)
response2 = chat.send_message("Can you give me a real-world example?")
print(response2.text)
# Third turn (full conversation context is preserved)
response3 = chat.send_message("How is that different from deep learning?")
print(response3.text)Streaming Responses
Get real-time output as it's generated:
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Streaming generation
stream = client.models.generate_content_stream(
model="gemini-2.5-pro",
contents="Write a short story about a robot learning to dream"
)
# Process chunks as they arrive
for chunk in stream:
print(chunk.text, end="", flush=True)Streaming is valuable for user-facing applications where displaying content as it arrives improves perceived responsiveness.
Image Processing with Python
Process images with Gemini:
from pathlib import Path
import base64
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# Load an image
image_path = "cat.jpg"
image_data = base64.standard_b64encode(Path(image_path).read_bytes()).decode("utf-8")
# Analyze the image
response = client.models.generate_content(
model="gemini-2.5-pro",
contents=[
{
"role": "user",
"parts": [
{"text": "Describe this image in detail"},
{
"inline_data": {
"mime_type": "image/jpeg",
"data": image_data,
}
},
],
}
],
)
print(response.text)TypeScript Quickstart
Installation
Install the Google AI TypeScript SDK:
npm install @google/generative-aiBasic Text Generation
Create your first TypeScript application:
import { GoogleGenerativeAI } from "@google/generative-ai";
const apiKey = process.env.GEMINI_API_KEY;
const client = new GoogleGenerativeAI(apiKey);
async function main() {
const model = client.getGenerativeModel({ model: "gemini-2.5-pro" });
const response = await model.generateContent(
"Explain artificial intelligence in one paragraph"
);
console.log(response.response.text());
}
main();Multi-Turn Conversations in TypeScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const apiKey = process.env.GEMINI_API_KEY;
const client = new GoogleGenerativeAI(apiKey);
async function main() {
const model = client.getGenerativeModel({ model: "gemini-2.5-pro" });
const chat = model.startChat({
history: [],
});
// First turn
let result = await chat.sendMessage("What is TypeScript?");
console.log(result.response.text());
// Second turn (context is maintained)
result = await chat.sendMessage("What are its main advantages?");
console.log(result.response.text());
}
main();Streaming in TypeScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const apiKey = process.env.GEMINI_API_KEY;
const client = new GoogleGenerativeAI(apiKey);
async function main() {
const model = client.getGenerativeModel({ model: "gemini-2.5-pro" });
const stream = await model.generateContentStream(
"Write a poem about the future of AI"
);
// Process stream chunks
for await (const chunk of stream.stream) {
const chunkText = chunk.candidates?.[0]?.content?.parts?.[0]?.text || "";
process.stdout.write(chunkText);
}
}
main();Safety Settings
Control content filtering with Safety Settings:
Python
from google.genai import types
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="Your prompt here",
safety_settings=[
types.SafetySetting(
category="HARM_CATEGORY_HATE_SPEECH",
threshold="BLOCK_MEDIUM_AND_ABOVE"
),
types.SafetySetting(
category="HARM_CATEGORY_DANGEROUS_CONTENT",
threshold="BLOCK_ONLY_HIGH"
),
]
)TypeScript
import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";
const client = new GoogleGenerativeAI(apiKey);
const model = client.getGenerativeModel({
model: "gemini-2.5-pro",
safetySettings: [
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
},
],
});Error Handling
Always implement proper error handling:
Python
try:
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="Your prompt"
)
print(response.text)
except genai.APIError as e:
print(f"API Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")TypeScript
try {
const response = await model.generateContent("Your prompt");
console.log(response.response.text());
} catch (error) {
if (error instanceof Error) {
console.error("Error:", error.message);
} else {
console.error("Unknown error occurred");
}
}Rate Limiting and Quotas
The free tier includes:
- 60 requests per minute
- 1.5 million tokens per month
- 1000 requests per day
Implement exponential backoff for rate limit handling:
Python
import time
import random
def generate_with_retry(client, prompt, max_retries=3):
for attempt in range(max_retries):
try:
return client.models.generate_content(
model="gemini-2.5-pro",
contents=prompt
)
except Exception as e:
if attempt < max_retries - 1:
wait_time = (2 ** attempt) + random.uniform(0, 1)
print(f"Rate limited. Waiting {wait_time:.2f}s...")
time.sleep(wait_time)
else:
raiseBest Practices
- Always use environment variables for API keys
- Implement error handling for production applications
- Use streaming for long responses to improve UX
- Set appropriate safety settings for your use case
- Monitor API usage to stay within quotas
- Test with cheaper models (Flash) before using Pro
- Cache responses when appropriate to reduce API calls
Next Steps
Now that you can make basic API calls, explore:
- Function calling for external tool integration
- Image and document processing
- Building multi-step AI workflows
- Deploying to production with proper monitoring
The Gemini API is flexible and powerful. Start simple, then layer in advanced features as your needs grow.