
API Access and Authentication: Connecting to Gemini
Your first lines of code. Learn how to install the Google Generative AI libraries, secure your API keys, and make your first authenticated request.
API Access and Authentication
You can't build an app in a web browser UI. You need to verify programmatically.
Installation
Google provides the google-generativeai SDK.
- Python:
pip install -U google-generativeai - Node.js:
npm install @google/generative-ai
Authentication
The SDK uses your API Key. Security Rule #1: Never hardcode the key.
Good Practice (.env):
- Create
.envfile:GEMINI_API_KEY=AIzaSy... - Use
python-dotenvto load it.
import os
from dotenv import load_dotenv
import google.generativeai as genai
load_dotenv()
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
REST API (cURL)
If you aren't using Python/JS, you can use raw HTTP requests.
curl -H 'Content-Type: application/json' \
-d '{"contents":[{"parts":[{"text":"Explain metrics"}]}]}' \
-X POST https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=YOUR_API_KEY
Summary
- Install the SDK.
- Use environment variables.
- The API endpoint pattern is
https://generativelanguage.googleapis.com/...
In the next lesson, we dive deep into the Python and JavaScript SDKs.