Gemini API in Python: Build and Check a First Request
The Gemini API Python SDK makes it straightforward to send a first request and handle the response. This guide walks through setup, a working call, failure handling, and keeping integration notes where your project can find them.
Updated 5 min read
The Gemini API Python SDK lets you send a prompt to a Google language model from a Python script, a notebook, or a server-side application. You install the library, configure a key, and make a request in fewer than ten lines of code. Tools like fenbs hold the integration brief, resolved problems and next implementation tasks so any assistant helping you build the project has the current context before each session.
For a broader introduction to the Gemini API before you write code, see Gemini API: a practical guide to your first workflow. For the Claude API in Python, see Claude API.
Install the SDK and configure your key
Install the Google Generative AI library with pip. Then get an API key from Google AI Studio at aistudio.google.com (opens in a new tab) and store it in an environment variable.
pip install google-generativeai
Do not paste the key directly into your Python file. Use an environment variable and load it at runtime. Add the .env file to .gitignore if you use python-dotenv.
import google.generativeai as genai import os genai.configure(api_key=os.environ["GEMINI_API_KEY"])
Send your first request
Create a model instance with a model name and an optional system instruction. The system instruction sets the model's behavior for every call: its task, the output format and any rules it must follow. Then call generate_content with the input text.
import google.generativeai as genai
import os
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
system_instruction="You are a concise assistant. Summarize in plain text, under 40 words.",
)
response = model.generate_content("Summarize this text: ...")
print(response.text)The response object contains the generated text in response.text. It also has a candidates list with additional metadata, including the finish reason. Check the finish reason when testing: a finish reason other than STOP means the model did not complete its output normally.
Set generation config to control the output
The GenerativeModel constructor accepts a generation_config parameter that adjusts how the model generates a response. The most useful settings are max_output_tokens, which limits the response length, and temperature, which controls how varied the outputs are. A lower temperature produces more consistent results; a higher one produces more varied ones.
import google.generativeai as genai
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
system_instruction="Summarize in plain text, under 40 words.",
generation_config=genai.GenerationConfig(
max_output_tokens=80,
temperature=0.2,
),
)For a summarization task, start with max_output_tokens set to slightly above your target word count and temperature at 0.2. Test with three representative inputs and compare to a run without the config to confirm the change has the intended effect. Write the config values and the reason for each in your project decisions, not just in the code.
Handle errors and finish reasons
Gemini API errors in Python raise exceptions. The main types to handle: authentication failures (wrong or expired key), quota exceeded (too many requests or too many tokens per day), and content safety blocks (the model declined to respond to the input). Each needs a different response.
import google.generativeai as genai
from google.api_core import exceptions as api_exceptions
import os
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
model = genai.GenerativeModel("gemini-1.5-flash")
try:
response = model.generate_content("Summarize: ...")
if response.candidates[0].finish_reason.name != "STOP":
# output is incomplete or was blocked
print(f"Unexpected finish: {response.candidates[0].finish_reason.name}")
else:
print(response.text)
except api_exceptions.PermissionDenied:
print("Authentication failed: check GEMINI_API_KEY")
except api_exceptions.ResourceExhausted:
print("Quota exceeded: wait and retry, or check your quota settings")Content safety blocks return a response with a finish reason of SAFETY or RECITATION rather than raising an exception. Always check the finish reason when the output is empty or shorter than expected.
Work with multimodal inputs
Gemini models accept text, images and documents in a single request. To send an image, load it with PIL or from a file path, and include it in the generate_content call alongside the text prompt. Test each input type separately before combining them: a mixed input behaves differently from a text-only one, even with the same system instruction.
Decide in advance which input types your integration will accept. A function that silently ignores an unsupported input type and returns a plausible-looking wrong answer is worse than one that raises a clear error. Write that decision into the integration before it reaches production.
Keep the integration brief and lessons across sessions
fenbs holds your integration requirements, the model version in use, the error handling decisions and the lessons from debugging. When an assistant opens the project in a new session, it reads those facts first so it does not re-derive what was already tried. Add the project now, write the first decision, and connect your AI tool from Integrations over MCP.
Create a free accountFree for one person · No credit card · Works with Claude, ChatGPT, Cursor and more
Test the output before using it
Test with at least three inputs you already understand before the integration processes anything live. For a summary task: check that the output does not add facts from outside the input, stays within the word limit, and handles a very short input without producing a longer output than the original.
Log the input and the output during development. When the output changes after a system instruction edit or a model update, the log shows exactly what changed and makes comparison straightforward. A log of ten test runs is worth more than a memory of one.
How to manage your Gemini Python project with fenbs
Write the shared record before your second session on the project, not after it is built. The context created early is the context every future session benefits from.
- Create a free account. Start with a personal board for a solo project.
- Add a project with a one-sentence goal, the model name in use, the system instruction version and the output format required.
- Add tasks for each phase: key setup, first request, error handling, output validation, production deployment. Move each to In Progress when you start.
- Record the integration lessons as you find them: input types that caused problems, prompt changes that improved consistency, quota limits you hit.
- Connect your AI coding assistant from Integrations over MCP. Ask it to read the project AI context at the start of each session, then save progress before it stops.