API Testing with Gemini 3.6 Flash: Complete Tutorial
Learn how to use Google's free Gemini 3.6 Flash model for API testing and automation.
Prerequisites
- Python 3.8+
-
requestslibrary:pip install requests - Google AI Studio API key (free at https://aistudio.google.com)
Quick Start
import requests
import os
import json
GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent"
def test_gemini_api(prompt: str, api_key: str = None) -> str:
"""Test Gemini API with a prompt."""
if api_key is None:
api_key = os.getenv("GEMINI_API_KEY")
url = f"{GEMINI_URL}?key={api_key}"
headers = {"Content-Type": "application/json"}
data = {
"contents": [{
"parts": [{"text": prompt}]
}],
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 1000,
"topP": 0.8
}
}
response = requests.post(url, headers=headers, json=data, timeout=30)
if response.status_code == 200:
return response.json()["candidates"][0]["content"]["parts"][0]["text"]
else:
raise Exception(f"Error: {response.status_code} - {response.text}")
# Test it
if __name__ == "__main__":
prompt = "Write a Python function to validate JSON API responses"
try:
result = test_gemini_api(prompt)
print(f"Prompt: {prompt}")
print(f"Response: {result}")
except Exception as e:
print(f"Error: {e}")
API Testing Use Cases
1. Generate Test Data
def generate_test_users(count: int = 5) -> list:
"""Generate realistic test user data."""
prompt = f"Generate {count} realistic JSON user objects with id, name, email, age, and address fields. Return as JSON array."
result = test_gemini_api(prompt)
return json.loads(result)
2. Create API Test Cases
def generate_test_cases(endpoint: str, method: str) -> list:
"""Generate test cases for an API endpoint."""
prompt = f"""Create 5 test cases for {method} {endpoint} API endpoint.
Include: positive, negative, edge cases, boundary values, auth tests.
Return as JSON array with: name, input, expected_status, expected_response."""
result = test_gemini_api(prompt)
return json.loads(result)
3. Validate API Responses
def validate_response(expected_schema: dict, actual_response: dict) -> dict:
"""Use AI to validate API response against expected schema."""
prompt = f"""Validate this JSON response against the expected schema.
Schema: {json.dumps(expected_schema)}
Response: {json.dumps(actual_response)}
Return: {{"valid": bool, "errors": [], "warnings": []}}"""
result = test_gemini_api(prompt)
return json.loads(result)
Error Handling & Rate Limits
import time
def robust_gemini_call(prompt: str, retries: int = 3, backoff: float = 2.0) -> str:
"""Call Gemini with exponential backoff for rate limits."""
for attempt in range(retries):
try:
return test_gemini_api(prompt)
except Exception as e:
if "429" in str(e) or "503" in str(e):
wait = backoff ** attempt
print(f"Rate limited. Waiting {wait}s... (attempt {attempt + 1}/{retries})")
time.sleep(wait)
else:
raise
raise Exception("Max retries exceeded")
Complete Test Suite Example
class APITester:
def __init__(self, base_url: str):
self.base_url = base_url
self.session = requests.Session()
def test_endpoint(self, endpoint: str, method: str = "GET", **kwargs) -> dict:
"""Test an API endpoint and return results."""
url = f"{self.base_url}{endpoint}"
response = self.session.request(method, url, timeout=10, **kwargs)
return {
"endpoint": endpoint,
"method": method,
"status": response.status_code,
"response_time": response.elapsed.total_seconds(),
"response": response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text
}
def run_test_suite(self, test_cases: list) -> list:
"""Run multiple test cases."""
results = []
for case in test_cases:
result = self.test_endpoint(case["endpoint"], case.get("method", "GET"))
result["test_name"] = case["name"]
result["passed"] = result["status"] == case.get("expected_status", 200)
results.append(result)
return results
# Usage
if __name__ == "__main__":
tester = APITester("https://jsonplaceholder.typicode.com")
test_cases = [
{"name": "Get posts", "endpoint": "/posts"},
{"name": "Get users", "endpoint": "/users"},
{"name": "Create post", "endpoint": "/posts", "method": "POST", "json": {"title": "test"}},
]
results = tester.run_test_suite(test_cases)
for r in results:
print(f"{r['test_name']}: {'PASS' if r['passed'] else 'FAIL'} - {r['status']} ({r['response_time']:.3f}s)")
Best Practices
- Use environment variables for API keys
- Set timeouts to prevent hanging requests
- Monitor rate limits - Free tier: 15 RPM for Gemini
- Cache responses during development
- Test edge cases - empty responses, large payloads, malformed data
- Log everything for debugging
Conclusion
Gemini 3.6 Flash provides a powerful free tier for API testing automation. Use it to generate test data, create test cases, validate responses, and build comprehensive test suites - all without API costs.
Top comments (1)
tr.ee/dev-to