Getting Started with the Gemini API
The Gemini API provides access to Google's powerful language models. This tutorial will guide you through the essential steps to start using the API in your projects.
1. Obtain an API Key
- Go to the Google AI Platform console.
- Create a new project or select an existing one.
- Enable the Generative Language API.
- Generate an API key and keep it secure.
2. Set Up Your Environment
Install the required Python package:
pip install google-generativeai
Set your API key as an environment variable:
import os
os.environ["GOOGLE_API_KEY"] = "YOUR_API_KEY"
3. Initialize the Client
import google.generativeai as genai
model = genai.GenModel("gemini-1.5-pro")
4. Make a Completion Request
Create a prompt and generate text:
prompt = "Explain quantum computing in simple terms."
response = model.generate(prompt)
print(response.text)
The generate method returns a Generation object. The text attribute contains the model's output.
5. Handle the Response
Access the generated text and usage information:
print(response.text) # Generated content
print(response.usage) # Token usage and cost
print(response.model) # Model name
6. Manage Costs
The API charges per million tokens. Monitor your usage to control costs. The free tier includes a limited number of tokens each month.
7. Error Handling
Network issues or invalid requests may raise exceptions. Use try/except blocks:
try:
response = model.generate(prompt)
except Exception as e:
print(f"Error: {e}")
8. Next Steps
- Try different models like
gemini-1.5-ultrafor higher quality. - Use the API for chat completions, embeddings, or batch requests.
- Integrate into web apps, bots, or data pipelines.
Conclusion
The Gemini API is easy to use and offers powerful capabilities. Follow these steps to start building AI applications today.
📦 Want the production-ready version?
This article covers the fundamentals. The AI Agent Architecture Patterns Library pack goes further — agent architecture, tool design and production guardrails, plus full source code and deployment configs.
→ Get AI Agent Architecture Patterns Library
Extracted from real production systems, not toy examples.
Top comments (0)