# InvalidArgument: 400 API key not valid. Stuck with this error

**URL:** <https://discuss.ai.google.dev/t/invalidargument-400-api-key-not-valid-stuck-with-this-error/40782>\
**Category:** Gemini API\
**Tags:** gemini-15, api\
**Created:** [September 27, 2024, 11:05pm UTC](https://discuss.ai.google.dev/t/invalidargument-400-api-key-not-valid-stuck-with-this-error/40782 "2024-09-27T23:05:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Abhimanyu\_Singh](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/abhimanyu_singh/32/25069_2.png) [@Abhimanyu\_Singh](https://discuss.ai.google.dev/u/Abhimanyu_Singh)\
**Post date:** [September 27, 2024, 11:05pm UTC](https://discuss.ai.google.dev/t/invalidargument-400-api-key-not-valid-stuck-with-this-error/40782/1 "2024-09-27T23:05:15Z")

</div>

I am not able to use Google API key. I tried a simple code to test the Google API Key using Pycharm community:

import os  
import google.generativeai as genai

from dotenv import load\_dotenv

load\_dotenv()

genai.configure(api\_key=os.getenv(“GOOGLE\_API\_KEY”))

model = genai.GenerativeModel(“gemini-1.5-flash”)  
response = model.generate\_content(“Write a story about a magic backpack.”)  
print(response.text)

It gives me error as:  
raise exceptions.from\_grpc\_error(exc) from exc  
google.api\_core.exceptions.InvalidArgument: 400 API key not valid. Please pass a valid API key. [reason: “API\_KEY\_INVALID”  
domain: “[googleapis.com](http://googleapis.com)”  
metadata {  
key: “service”  
value: “[generativelanguage.googleapis.com](http://generativelanguage.googleapis.com)”

What could be the reason for this error and how do I resolve it?

---

<div class="post-metadata">

**Author:** ![afirstenberg](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/afirstenberg/32/202_2.png) [@afirstenberg](https://discuss.ai.google.dev/u/afirstenberg)\
**Post date:** [September 28, 2024, 2:13pm UTC](https://discuss.ai.google.dev/t/invalidargument-400-api-key-not-valid-stuck-with-this-error/40782/2 "2024-09-28T14:13:19Z")

</div>

Welcome to the forums!

The usual cause for problems like this are not setting the API Key correctly in your environment.

Can you show us how you’re setting the key? (Without showing us the key itself.)

---

<div class="post-metadata">

**Author:** ![system](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/system/32/1_2.png) [@system](https://discuss.ai.google.dev/u/system)\
**Post date:** [November 5, 2026, 6:17pm UTC](https://discuss.ai.google.dev/t/invalidargument-400-api-key-not-valid-stuck-with-this-error/40782/4 "2026-11-05T18:17:50Z")

</div>

Closed on November 5, 2026, 6:17pm UTC

This thread was automatically closed 60 days after the last reply. If you are running into an issue, please create a new post.
