Gemini API Tutorial via OpenRouter
Gemini API Tutorial via OpenRouter This tutorial will guide you through using the Gemini API through OpenRouter's free endpoint. We'll cover setting up the request, making a simple completion call, and interpreting the
Gemini API Tutorial via OpenRouter
This tutorial will guide you through using the Gemini API through OpenRouter's free endpoint. We'll cover setting up the request, making a simple completion call, and interpreting the response.
Prerequisites
- An OpenRouter API key (obtainable from https://openrouter.ai)
- Python 3.x
- requests library (
pip install requests)
Installation
pip install requests
Example Code
import requests
API_KEY = "your_openrouter_api_key"
ENDPOINT = "https://api.openrouter.ai/v1/chat/completions"
def get_gemini_response(user_message):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": "google/gemini-2.0-flash-exp",
"messages": [{"role": "user", "content": user_message}]
}
response = requests.post(ENDPOINT, json=payload, headers=headers)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
if __name__ == "__main__":
user_input = input("Ask Gemini: ")
print("Gemini says:", get_gemini_response(user_input))
Explanation
-
Endpoint:
https://api.openrouter.ai/v1/chat/completionsis the unified endpoint used by OpenRouter to reach various LLM providers. -
Model: We use
google/gemini-2.0-flash-expas an example; replace with any compatible model. - Headers: Authorization with Bearer token and Content-Type JSON.
-
Payload: The
modelfield specifies which LLM to use, andmessagescontains the conversation history.
Running the Script
Save the script as gemini_tutorial.py and run:
python gemini_tutorial.py
Enter your message when prompted, and the script will display Gemini's response.
Tips
- Use the free tier of OpenRouter to test without spending credits.
- Adjust the
modelparameter to try different Gemini variants. - Handle rate limits by checking the response status code.
By following this tutorial, you'll be able to integrate Gemini into your applications using OpenRouter's API gateway.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.