Gemini API not working

I have a simple test code :
import requests
api_key = “XXX”
url = “https://api.geminiai.com/v1/models/gemini-1.5-flash/generate
headers = {
“Authorization”: f"Bearer {api_key}",
“Content-Type”: “application/json”
}
payload = {
“prompt”: “Write a poem about a cat.”
}

response = requests.post(url, headers=headers, json=payload)

if response.status_code == 200:
response_data = response.json()
generated_text = response_data[‘result’][‘candidates’][0][‘content’][‘text’]
print(generated_text)
else:
print(“Error:”, response.status_code, response.text)

This simple code to test Gemini API is not working , I am getting this error

requests.exceptions.ConnectionError: HTTPSConnectionPool(host=‘api.geminiai.com’, port=443): Max retries exceeded with url: /v1/models/gemini-1.5-flash/generate (Caused by NameResolutionError(“<urllib3.connection.HTTPSConnection object at 0x10586f490>: Failed to resolve ([Errno 8] nodename nor servname provided, or not known)”))

I used an equivalent curl request just to ensure my key is working that that seems to be fine. Can someone point out the mistake in code or setup

Welcome to the forum.

The error message says, the hostname could not be resolved. Use this https://generativelanguage.googleapis.com/ instead of api.geminiai.com

The operation is not called generate, it is :generateContent appended right after the model name.

With these changes, you should at least get to the right servers and start receiving http error code 400 responses. You will need to work on your json payload to get past the 400. This documentation reference shows valid payload Generating content  |  Gemini API  |  Google AI for Developers

Hope that helps.