AI

Troubleshooting Gemini API: Why It Is Not Working

When your Gemini API calls start failing, it is usually due to quota exhaustion, invalid JSON formatting, or schema mismatch. Here is how to debug it.

By · · 7 min read

Short answer

If your Gemini API request is failing, first check your API key, ensure your payload follows the correct content-type header, and handle 429 rate limits with exponential backoff. Most issues stem from invalid JSON structures, schema mismatches, or exceeding your project quota in the Google AI Studio console.

Key takeaways

  • Use direct REST requests instead of SDKs to see exact raw error responses.
  • Implement exponential backoff to handle 429 Rate Limit errors effectively.
  • Validate your JSON schema strictly, as Gemini is sensitive to malformed requests.
  • Check the Google AI Studio console to verify project-level quotas.

Why is the Gemini API returning 400 Bad Request?

A 400 error in the Gemini API usually indicates an issue with the structure of your payload. The most common culprit is a missing or incorrect Content-Type header. You must set this to application/json in your request headers to ensure the server processes the data body correctly as a structured object.

Even when the header is correct, the API is highly sensitive to the exact structure of your JSON data. A trailing comma at the end of an array or an mismatched bracket will cause the parsing engine to reject the entire request immediately. Developers often overlook characters that are invisible in code editors but invalid in the JSON standard.

When you encounter this, print your entire request object to the console directly before sending it to the endpoint. Verify that all required keys are present and that your prompt content is wrapped in the expected 'contents' array structure. If you are sending images or multipart data, ensure the boundaries are correctly defined, as slight deviations from the documentation will result in a 400 response without specific field error messages.

To debug this effectively, break down the request. Send the absolute minimal payload that should technically function. Once the API accepts this baseline, add your specific parameters and formatting back in one at a time. This process of elimination identifies the specific field that is causing the validation error.

How to fix Gemini API 429 rate limit errors?

A 429 error occurs when you exceed the Requests Per Minute (RPM) or Tokens Per Minute (TPM) limits set for your tier in the Google AI Studio settings. Do not simply ignore these or attempt to retry immediately, as this creates a positive feedback loop that delays your recovery.

You must implement an exponential backoff strategy in your code to manage these limits properly. Instead of retrying right after a failure, you wait for a short duration—typically starting at one second—and then double that time for every subsequent failed request.

This approach prevents your system from constantly hitting the API when it is clearly overloaded. By spreading out your retry attempts, you provide the service time to clear the internal quota buckets. This ensures your background workers remain stable rather than crashing due to repeated connection failures.

To improve your backoff logic, consider adding a random jitter component to the wait time. Jitter adds a small, variable duration to your calculated wait time, preventing a thundering herd where multiple server instances attempt to retry at the exact same millisecond. This variance is crucial for distributed systems that share the same API credentials.

import time
import requests
import random

def call_gemini_with_retry(payload, url, headers):
    retries = 5
    for i in range(retries):
        response = requests.post(url, json=payload, headers=headers)
        if response.status_code == 429:
            # Add jitter to exponential backoff
            sleep_time = (2 ** i) + random.random()
            time.sleep(sleep_time)
            continue
        return response
    raise Exception('Max retries exceeded')

Debugging schema and function calling mismatches

When using structured output or function calling, Gemini expects a very specific response schema. If your defined schema does not match the generated output type, the API might reject the request or fail to parse the tool calls. This typically happens when the model generates a string where a number is expected, or an empty object instead of a mandatory list.

If you are experiencing consistent issues, simplify your schema to the bare minimum fields first. Validate your schema using external JSON tools before passing it to the API, as a small definition error in the JSON structure will prevent the model from successfully mapping its output to your code requirements.

Once you have a successful round-trip with the simplest possible configuration, add more complex validation logic such as nested objects or lists one by one. This incremental verification allows you to isolate which part of the complex schema is causing the interpretation failure.

Check that your function descriptions are clear and unambiguous. If the model cannot determine which tool to call because your function descriptions are too similar, it will fail to return a valid JSON object. Being verbose in your function definitions helps the model select the correct tool and provide data that conforms to your schema.

Is your API key authorized?

If you receive a 403 Forbidden error, your API key is either invalid or lacks the necessary permissions for the specific project associated with your request. Check your Google AI Studio dashboard to ensure the key is active and that your API project has the Gemini service enabled.

If you are using environment variables, verify that the key is being loaded correctly into your server runtime. A common mistake in production is having an empty string as your key due to misconfigured deployment settings on platforms like Vercel, Netlify, or AWS Lambda. The server may be running, but the authentication token is missing or malformed.

Inspect your CI/CD configuration to confirm that environment secrets are actually being injected into the runtime environment. In some cases, secret management tools require you to explicitly map variables to the application's process space. If the variable is named differently in your local .env file versus the production environment variables console, your application will fail to authenticate.

Additionally, verify that there are no IP restrictions or domain restrictions on your API key within the Google Cloud console. If you have restricted your key to only be usable from specific server IP addresses, requests made from different infrastructure will be denied regardless of whether the key is valid.

Best practices for production error handling

Never rely solely on SDKs in production. By using raw REST calls, you can inspect headers, status codes, and raw JSON responses directly. This visibility is essential for diagnosing transient network errors versus application-level logic errors that might be obscured by the abstraction layer of an SDK.

Always implement robust logging for the raw request and response data when a failure occurs. This data is invaluable when you need to reproduce issues locally that only manifest in your production environment. If you only log the error code, you lose the detailed explanation usually provided by the API inside the response body.

Use a structured logging system to track the lifecycle of your API requests. If a request fails, record the timestamp, the payload (sanitized of sensitive data), the status code, and the response body. This creates an audit trail that allows you to identify patterns in your failures, such as whether they occur at specific times of the day or with specific types of prompts.

Consider the use of a centralized logging service that aggregates output from all your server instances. This makes it easier to query for failed requests across distributed nodes, ensuring that you do not miss error logs scattered across different temporary containers.

Status CodeMost Likely CauseAction
400Invalid JSON or schemaValidate payload format
403Invalid key or permissionsCheck Google AI Studio
429Rate limit exceededImplement exponential backoff
500Server-side errorRetry after a delay

Gotchas and common pitfalls

One major pitfall is ignoring the response body during a 400 error. The response usually contains a helpful message detailing exactly which field failed validation. Always log 'response.json()' when status codes are not 200, as this is often where the API explains what it did not like about your request.

Another issue is time-sensitive deployments. If your server function on Vercel times out while waiting for a heavy Gemini response, you will get a 504 error. This happens because the model takes longer to generate the response than the platform's default execution limit allows. Ensure your serverless functions have enough execution time or move long-running tasks to a background worker to avoid these premature timeouts.

Be aware of the size of your input prompts. Gemini has specific token limits, and sending excessively large documents or images can cause the request to hang or fail. If you are processing long documents, break them into smaller chunks and process them sequentially to stay within the window of the API.

Finally, monitor your usage of the 'model' parameter. Using an older or deprecated version of the Gemini model can result in unexpected behavior or performance degradation. Periodically update your endpoint configuration to ensure you are utilizing the latest stable model versions supported by your project.

Frequently asked questions

How do I implement exponential backoff?

Catch the 429 status code in your response handling logic. Use a loop that waits for a duration, starting at one second, and double that duration after every retry attempt until the request succeeds or a maximum attempt count is reached.

Can I use Gemini API without an SDK?

Yes, you can use standard HTTP clients like fetch, axios, or requests. This method is often preferred for production because it gives you full control over headers and enables easier debugging of raw API responses.

Where do I check my API usage limits?

Navigate to the Google AI Studio console and select the project associated with your API key. The dashboard displays your current usage, rate limits, and any quota alerts that may be affecting your application's connectivity.

Sources & further reading

Work with me

Building something like this?

I build AI-powered products with Next.js, Python and LLM APIs, from first prototype to production. If you need help with a project, a second opinion on your architecture, or a developer on your team, get in touch.

About the author

Tushar Gautam is a full-stack & ai product engineer in India. He builds AI SaaS products such as an AI video ad generator, a RAG chatbot platform and a Razorpay-powered report service, mostly with Next.js, Flask and the Gemini API. See the projects, GitHub or LinkedIn.

This article was drafted with the help of AI (Google Gemini) from official documentation and published by Tushar Gautam. Spotted an error? Let me know.