Last modified: Nov 12, 2024 By Alexander Williams
Using Google Gemini API in Python
Integrating Google Gemini API in Python can unlock robust data-driven insights. Here’s how to get started.
Understanding Google Gemini API
Google Gemini API provides programmatic access to various Google services, enabling you to extract valuable data for your projects.
Before using the API, ensure you have a Google Cloud account and the necessary API credentials.
Setting Up the Environment
To begin, install the required Python packages. You’ll need requests
to make API calls.
pip install requests
Authentication with Google Gemini API
To authenticate, you’ll use an API key or OAuth 2.0 credentials. Here’s how to set up your authentication method:
Using an API key is simpler but may have limited access. Alternatively, OAuth 2.0 provides enhanced permissions.
Using API Key
Place your API key in the request header for a secure connection.
import requests
api_key = "YOUR_API_KEY"
url = "https://gemini.googleapis.com/v1/your_endpoint"
headers = {
"Authorization": f"Bearer {api_key}"
}
response = requests.get(url, headers=headers)
print(response.json())
Note: Replace YOUR_API_KEY
with your actual API key.
Using OAuth 2.0
For more robust security, use OAuth 2.0. Google provides a library, google-auth
, for this purpose.
pip install google-auth
Once installed, create OAuth credentials in the Google Cloud Console. Download the JSON file with your credentials.
from google.oauth2 import service_account
import requests
credentials = service_account.Credentials.from_service_account_file("path/to/credentials.json")
scoped_credentials = credentials.with_scopes(["https://www.googleapis.com/auth/gemini.readonly"])
url = "https://gemini.googleapis.com/v1/your_endpoint"
headers = {
"Authorization": f"Bearer {scoped_credentials.token}"
}
response = requests.get(url, headers=headers)
print(response.json())
Making Requests with the API
With authentication in place, you can start making requests. Here’s an example:
import requests
def get_data(endpoint, headers):
url = f"https://gemini.googleapis.com/v1/{endpoint}"
response = requests.get(url, headers=headers)
return response.json()
data = get_data("projects/your_project_id", headers)
print(data)
Tip: Ensure to replace your_project_id
with your actual project ID in the code.
Handling API Response
Responses are typically in JSON format, which is easy to parse in Python. Here’s how to parse a JSON response:
import json
data = response.json()
print(json.dumps(data, indent=4))
Conclusion
Integrating the Google Gemini API with Python provides a powerful way to leverage Google’s data services. By following these steps, you can start making authenticated API requests and handling responses effectively.