API Access and Authentication: Connecting to Gemini

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):

  1. Create .env file: GEMINI_API_KEY=AIzaSy...
  2. Use python-dotenv to 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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn