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

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
metadata {
key: “service”
value: “generativelanguage.googleapis.com

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

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.)