Date: 30 January 2026
API Key Security
Treat API keys as passwords - never expose publicly. Keys grant access to account, consume quota, incur charges if exposed and abused. Security practices prevent unauthorized usage and unexpected bills.
Security Best Practices:
- Never commit keys to public GitHub repositories
- Use environment variables storing keys outside code
- Implement key rotation changing keys periodically
- Enable domain restrictions limiting key usage to specific sites
- Monitor usage detecting unauthorized access quickly
- Separate development and production keys
Environment variables store keys securely without hardcoding. Configuration files outside version control load keys at runtime. Different approaches for various platforms.
Environment Variable Examples:
bash
# Linux/Mac
export GEOCODING_API_KEY="your_key_here"
# Windows Command Prompt
set GEOCODING_API_KEY=your_key_here
# Windows PowerShell
$env:GEOCODING_API_KEY="your_key_here"
JavaScript applications access environment variables through process.env.GEOCODING_API_KEY. Python uses os.environ['GEOCODING_API_KEY']. Framework-specific methods exist for Rails, Django, Laravel loading configuration securely.
Domain restrictions limit key usage to specified websites preventing stolen keys working on attacker domains. Configure allowed domains in dashboard - whitelist your production domain and localhost for development.
Key rotation changes keys periodically limiting exposure window if compromise occurs. Generate new key, update applications, delete old key. Quarterly rotation reasonable balance between security and operational burden.
Testing API Key
Verify key works correctly before building application features. Simple test request confirms authentication and basic functionality.
cURL Test Command:
bash
curl "https://api.distancematrix.ai/geocode?address=1600+Amphitheatre+Parkway+Mountain+View+CA&key=YOUR_API_KEY"
Replace YOUR_API_KEY with actual key from dashboard. Successful response returns JSON with coordinates, formatted address, location components.
Expected Response:
json
{
"status": "OK",
"results": [{
"formatted_address": "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry": {
"location": {
"lat": 37.4224764,
"lng": -122.0842499
}
}
}]
}
Status "OK" indicates successful geocoding. Coordinates appear in geometry.location object. Formatted address shows standardized version of input.
Error responses indicate problems requiring resolution. "REQUEST_DENIED" suggests invalid key or domain restrictions. "OVER_QUERY_LIMIT" means rate limit exceeded. "INVALID_REQUEST" indicates malformed query.
Implementing in Applications
JavaScript implementation uses fetch API or axios library making HTTP requests to geocoding endpoint.
JavaScript Example:
javascript
const apiKey = process.env.GEOCODING_API_KEY;
const address = '1600 Amphitheatre Parkway, Mountain View, CA';
fetch(`https://api.distancematrix.ai/geocode?address=${encodeURIComponent(address)}&key=${apiKey}`)
.then(response => response.json())
.then(data => {
if (data.status === 'OK') {
const location = data.results[0].geometry.location;
console.log(`Latitude: ${location.lat}, Longitude: ${location.lng}`);
}
});
URL encoding addresses handles spaces and special characters properly. encodeURIComponent() converts addresses into URL-safe format.
Python requests library simplifies HTTP calls with clean syntax.
Python Example:
python
import os
import requests
api_key = os.environ['GEOCODING_API_KEY']
address = '1600 Amphitheatre Parkway, Mountain View, CA'
response = requests.get(
'https://api.distancematrix.ai/geocode',
params={'address': address, 'key': api_key}
)
data = response.json()
if data['status'] == 'OK':
location = data['results'][0]['geometry']['location']
print(f"Latitude: {location['lat']}, Longitude: {location['lng']}")
Requests library handles URL encoding automatically when using params dictionary. Cleaner than manual string concatenation.
Rate Limiting and Quotas
Free tier provides 5,000 requests monthly - approximately 167 daily. Development and testing typically fits within free quota. Production applications may require paid plans.
Usage Planning:
- Development/testing: 100-500 requests daily
- Small production app: 1,000-5,000 monthly
- Growing app: 10,000-50,000 monthly
- Established app: 100,000+ monthly
Rate limiting prevents exceeding quotas. Implement retry logic with exponential backoff handling temporary rate limit errors. Cache geocoding results avoiding redundant requests for same addresses.
Monitoring usage through dashboard prevents surprise quota exhaustion. Set up alerts notifying approaching limits. Proactive monitoring enables upgrading before service disruption.
Caching Strategies
Caching geocoded results dramatically reduces API calls. Same addresses geocoded repeatedly waste quota and slow applications.
Caching Approaches:
- In-memory cache: Fast but lost on restart
- Database storage: Persistent across restarts
- Redis/Memcached: Distributed caching for scaled apps
- Local storage: Browser-based caching for web apps
Cache TTL (time-to-live) balances freshness against efficiency. Addresses rarely change - days or weeks appropriate TTL. Coordinates essentially permanent once geocoded.
Cache key design affects hit rate. Normalize addresses before caching - lowercase, remove extra spaces, standardize formatting. "123 Main St" and "123 main street" should hit same cache entry.
Error Handling
Robust error handling prevents application failures from geocoding issues. Network problems, invalid addresses, rate limits all require graceful handling.
Common Errors:
- ZERO_RESULTS: Address not found, try variations
- INVALID_REQUEST: Malformed query parameters
- REQUEST_DENIED: Invalid API key or restrictions
- OVER_QUERY_LIMIT: Rate limit exceeded, implement backoff
- UNKNOWN_ERROR: Temporary issue, retry with delay
Fallback strategies maintain functionality despite geocoding failures. Default coordinates, approximations, user notification all viable approaches depending on use case criticality.
User input validation reduces invalid requests. Check address field not empty. Validate basic format before API call. Client-side validation prevents wasting quota on obvious errors.
Production Deployment
Environment configuration separates development and production keys. Development key for local testing. Production key with domain restrictions for live site. Separation prevents accidental production quota consumption during development.
Monitoring and alerting track production usage patterns. Sudden spikes indicate problems or abuse. Gradual growth shows healthy application adoption. Anomaly detection enables quick response to issues.
Budget planning accounts for geocoding costs at scale. Calculate expected monthly requests based on user activity projections. Understand cost per user or transaction. Ensure pricing model supports API expenses.
Upgrading Plans
Free tier adequate for initial development and small applications. Growing beyond 5,000 monthly requests requires paid plan.
Paid pricing $49 per 100,000 requests ($0.49 per 1,000) scales economically. Clear transparent pricing without hidden fees or complex tiers. Calculate costs accurately using straightforward rate.
Enterprise options available for very high volume. Custom pricing, dedicated support, SLA guarantees. Contact sales when exceeding several million requests monthly.
Getting geocoding API key from DistanceMatrix.ai takes minutes providing immediate development access. Free tier supports testing and small applications. Security best practices protect keys from unauthorized use. Caching and error handling optimize quota usage and reliability. Straightforward pricing scales economically as applications grow. Developers gain location capabilities quickly without complex signup processes or expensive commitments enabling rapid application development and deployment.

.webp)

