Getting Started with the Gemini API
The Gemini API is a powerful tool for developers to integrate AI capabilities into their applications. In this tutorial, we'll walk through the basics of using the Gemini API to generate text. The API is accessible via a simple HTTP endpoint and returns JSON responses.
Prerequisites
To get started, you'll need:
- Python 3.6 or higher
- The
requestslibrary (install withpip install requests)
Step 1: Get Your API Key
To use the Gemini API, you need an API key. You can obtain one by signing up at the Unorouter platform (or your preferred provider). Once you have your key, you can use it in your code. The key is a string that you include in the Authorization header of your requests.
Step 2: Write the API Request
Here's a simple Python example to call the Gemini API:
import requests
api_key = "YOUR_API_KEY"
url = "https://api.unorouter.com/v1/chat/completions"
payload = {
"model": "gemini-3.6-flash:free",
"messages": [{"role": "user", "content": "Hello, world!"}]
}
response = requests.post(url, json=payload, headers={"Authorization": f"Bearer {api_key}"})
if response.status_code == 200:
data = response.json()
print(data["choices"][0]["message"]["content"])
else:
print(f"Error: {response.status_code}")
This code sends a POST request to the API endpoint with a JSON payload. The model parameter specifies which model to use (in this case, the free Gemini model). The messages array contains the user's query.
Step 3: Interpret the Response
The response will be a JSON object. The choices array contains the generated text. The first element in the array (index 0) is the response from the model. The message object within the first choice contains the actual text.
Error Handling and Best Practices
When working with the API, it's important to handle errors gracefully. Common errors include:
- Invalid API key (401 Unauthorized)
- Invalid request (400 Bad Request)
- Rate limiting (429 Too Many Requests)
Always check the response status code and handle errors appropriately. Also, consider using exponential backoff for rate-limited requests.
Conclusion
The Gemini API is straightforward to use and offers a free tier for development. With just a few lines of code, you can integrate AI into your applications. Start experimenting today!
Top comments (0)