Getting your API key
Visit Google AI Studio
Navigate to Google AI Studio to generate your API key.
Create or select a project
Choose an existing Google Cloud project or create a new one to associate with your API key.
Saving the API key
GemAI uses theSaveApiKeyUseCase to securely store your API key in the app’s DataStore. The key is persisted locally and encrypted by the Android system.
SaveApiKeyUseCase.kt
DatastoreRepositoryImpl.kt
Retrieving the API key
To retrieve the stored API key, GemAI uses theGetApiKeyUseCase:
GetApiKeyUseCase.kt
Validating the API key
Before saving an API key, you should validate it to ensure it works correctly. GemAI provides atestKey() function in the ModelBuilder class:
ModelBuilder.kt
The validation function sends a simple test message to the Gemini API using the
gemini-1.5-flash model. If the request succeeds, the key is valid.How it works
ThetestKey() function:
- Creates a temporary
GenerativeModelinstance with the provided API key - Sends a test prompt (“Hi, how are you?”) to the Gemini API
- Returns
trueif the request succeeds,falseif an exception occurs
User configuration
The API key is stored as part of theUserConfig data class:
UserConfig.kt
The stored API key, or
null if not yet configuredFlag indicating whether a valid API key has been saved
The selected AI model to use with the API key
Security best practices
Follow these guidelines to keep your API key secure:
- Never hardcode API keys in your source code
- Use environment variables or secure storage mechanisms during development
- Rotate keys regularly if you suspect they’ve been compromised
- Monitor usage in the Google Cloud Console to detect unauthorized access
- Enable billing alerts to catch unexpected API usage
Troubleshooting
Invalid API key error
If thetestKey() function returns false, verify:
- The API key is copied correctly without extra spaces
- The API key is enabled in Google Cloud Console
- The Generative AI API is enabled for your project
- Your Google Cloud project has billing enabled
Key not persisting
If your API key doesn’t persist between app sessions:- Check that DataStore has write permissions
- Verify the app isn’t clearing data on restart
- Ensure the
SaveApiKeyUseCaseis being called successfully