🛡️ 500+ Free Excel, VBA, Outlook & Python Guides — Tested & Copy-Ready Explore 150+ VBA Macros →

How to Use Gemini API in Python – Send Prompt and Get Response

Gemini API in Python - Send Prompt & Get Response

Most of us use Google Gemini by typing a question in the chat window & copying the answer back. It is fine for one or two questions. But, what if you have 500 product descriptions to rewrite, or a list of customer emails to summarize every day?

Typing each one in the browser is not practical. In this case, we can call Gemini from a Python program, send the prompt & get the response back as plain text. Then the output can be saved to a text file, CSV or Excel, whatever you need.

In this page you will get the Python code to do exactly that, with few more useful variations like chat with memory and calling the API without any library.

Also Read: How to use Gemini API in Excel VBA Macro

Step 1: Get Gemini API Key from Google AI Studio

Before writing any code, we need an API key. This is like a password that tells Google, the request is coming from your account.

  1. Open Google AI Studio & login with your Google account.
  2. Click on "Create API key" button.
  3. Copy the key & keep it in a safe place.

Note: Do not share this key with anyone or upload it to Github along with your code. Anybody with this key can use your quota. There is a free tier with limited requests per minute, and the limits keep changing. So, check the pricing page in AI Studio for the latest details.

For more details on the free tier & its limits, read How to Get Free Gemini API Key & Rate Limits.

Step 2: Install Gemini Python Library

Google provides an official Python library called google-genai. Open the command prompt & run this command.

pip install -U google-genai

If you do not have Python in your computer yet, read this first: How to Install Python in Windows.

You may see many old articles in internet using "import google.generativeai as genai". That is the older library (google-generativeai) & Google has stopped supporting it. So, use the new google-genai package as explained here. The import line looks almost same, so do not get confused.

Next, save the API key as an environment variable. This way, we don't have to type the key inside the code.

:: Windows Command Prompt (close & reopen the command prompt after this)
setx GEMINI_API_KEY "paste-your-api-key-here"

# Linux or Mac Terminal
export GEMINI_API_KEY="paste-your-api-key-here"

The library automatically looks for this variable name i.e., GEMINI_API_KEY. If it is set, then nothing else is needed.

Python Code - Send Prompt to Gemini & Get Response

Now, here is the simple code. Copy this to a new file, save it as ask_gemini.py & run it.

# Send a prompt to Google Gemini & print the reply
from google import genai

# Client reads the key from GEMINI_API_KEY environment variable.
# If you have not set it, pass it here: genai.Client(api_key="YOUR_API_KEY")
client = genai.Client()

# Gemini model to use. Change this when Google releases a newer model.
modelName = "gemini-3.8-flash"

# Get the question from user
userPrompt = input("Ask Gemini : ")

# Send the prompt to Gemini API
response = client.models.generate_content(
    model=modelName,
    contents=userPrompt
)

# Print the response text
print("Gemini Reply :")
print(response.text)

When you run this, it will ask for a question. Type something like "Explain VLOOKUP in 3 lines" & press Enter. In few seconds, the answer from Gemini will be printed.

The important part is generate_content. It takes 2 parameters.

  1. model: Which Gemini model should answer. Flash models are fast & cheap, good enough for most of the daily tasks.
  2. contents: The prompt text that you want to send.

The reply comes back as a response object. response.text gives only the text part of the answer, which is what we need most of the time.

Give Instructions to Gemini - System Prompt

Sometimes we want Gemini to answer in a particular way. For example, always in simple English, or always in bullet points. Instead of adding this to every question, we can pass it once as a system instruction.

from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="How do I remove duplicates in Excel?",
    config=types.GenerateContentConfig(
        system_instruction="You are an Excel trainer. Answer in simple English, in less than 100 words."
    )
)

print(response.text)

Chat with Gemini - Ask Follow up Questions

The above code does not remember the previous question. Every call is a fresh one. If you want a chat like conversation, where Gemini remembers what was asked earlier, then use the chat option.

from google import genai

client = genai.Client()
chat = client.chats.create(model="gemini-3.8-flash")

print("Type 'exit' to stop the chat")
while True:
    userPrompt = input("You    : ")
    if userPrompt.lower() == "exit":
        break

    reply = chat.send_message(userPrompt)
    print("Gemini : " + reply.text)

Try asking "What is the capital of Japan?" & then "What is its population?". Gemini will understand that "its" means Tokyo, because the chat object sends the old messages also along with the new one.

Call Gemini API without Library - Using Requests

In some office computers, installing new packages is blocked. Or you may just want to understand what is happening behind the library. Gemini also has a REST API. So, we can call it directly with the requests module, similar to how we got the weather report using Python.

# Call Gemini REST API directly - no SDK needed
import os
import requests

apiKey = os.environ["GEMINI_API_KEY"]
modelName = "gemini-3.8-flash"

apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/" + modelName + ":generateContent"

headers = {
    "x-goog-api-key": apiKey,
    "Content-Type": "application/json"
}

# Prompt has to be sent in this JSON format
requestBody = {
    "contents": [
        {"parts": [{"text": "What is the capital of Australia?"}]}
    ]
}

response = requests.post(apiUrl, headers=headers, json=requestBody, timeout=60)

# Check Return Code from API Server & Proceed
if response.status_code != 200:
    print("Error Code : " + str(response.status_code))
    print(response.text)
else:
    jsonData = response.json()
    print(jsonData["candidates"][0]["content"]["parts"][0]["text"])

The JSON returned from the API will look something similar to this one. The answer text is inside candidates -> content -> parts. If you are new to reading JSON in Python, refer this Python JSON parser article.

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "The capital of Australia is Canberra."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 8,
    "candidatesTokenCount": 8,
    "totalTokenCount": 16
  },
  "modelVersion": "gemini-3.8-flash"
}

The usageMetadata part tells how many tokens are used. This is useful if you are on a paid plan & want to keep track of the cost.

Common Errors & How to Fix them

These are the errors I see most often when running the above code for the first time.

  • 400 - API key not valid: Key is copied wrongly or has extra space. Also, if you used setx, then close the command prompt & open a new one. Old windows will not see the new variable.
  • 404 - Model not found: Model name is wrong or the model is retired. Google replaces models quite often. Use the code below to get the list of models available for your key.
  • 429 - Resource exhausted: You have crossed the free tier limit. Wait for a minute & try again. If you are sending prompts in a loop, add time.sleep(2) between each call.
  • ModuleNotFoundError: No module named 'google': The library is installed in a different Python. Run python -m pip install -U google-genai using the same python that runs your script.
from google import genai

client = genai.Client()

# Print all model names available for this API key
for model in client.models.list():
    print(model.name)

Note: Google has also introduced a newer "Interactions API" (client.interactions.create) for building agents & long running tasks. For a simple send prompt & get response requirement, generate_content explained above works perfectly fine & most of the sample codes in internet are still based on it.

Once this basic code is working, you can read a list of prompts from an Excel or CSV file, send each one to Gemini & write the responses back. If you want to share this as a tool with your colleagues who do not have Python, you can also convert the Python script to an exe file.