How to Call the Gemini API from Python
Install the google-genai SDK and generate text from Gemini in a few lines of Python.
When you want Gemini inside a script or app rather than the terminal, the official Python SDK is the cleanest route. The package is google-genai, and it reads your API key from the environment so no secrets end up in code. This guide gets a first generation working.
What you need
- Python 3.9 or newer
- A Gemini API key in the GEMINI_API_KEY environment variable
- pip for installing packages
- About 5 minutes
Step 1: Install the SDK
Install the google-genai package into your project, ideally inside a virtual environment so it does not pollute your system Python.
python -m venv .venv
source .venv/bin/activate
pip install google-genaiStep 2: Write a minimal script
Create a file and import the client. With no key passed explicitly, the SDK looks for GEMINI_API_KEY automatically. Pick a current model such as gemini-2.5-flash, which is fast and inexpensive for everyday work.
from google import genai
client = genai.Client() # reads GEMINI_API_KEY from the environment
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Write a one-line git commit message for fixing a null pointer in auth.",
)
print(response.text)Step 3: Run it
Execute the script. If the key is set correctly you get a single generated line printed to your terminal.
Result
You can now generate text from Gemini in any Python program. From here you can loop over inputs, feed it file contents, or wire it into a web handler, all on the same client.models.generate_content call.
Watch related tutorials
16:12
25:00
14:00
15:00
1:42:18
28:14