test-api-key.ts.jsā¢3.22 kB
#!/usr/bin/env node
import axios from "axios";
import * as dotenv from "dotenv";
// Load environment variables
dotenv.config();
async function testGooglePlacesAPI() {
const apiKey = process.env.GOOGLE_MAPS_API_KEY;
if (!apiKey) {
console.error("ā Error: GOOGLE_MAPS_API_KEY environment variable is not set");
console.log("\nPlease create a .env file with:");
console.log("GOOGLE_MAPS_API_KEY=your_api_key_here");
process.exit(1);
}
console.log("š Testing Google Places API Key...");
console.log(`š API Key: ${apiKey.substring(0, 10)}...${apiKey.substring(apiKey.length - 4)}`);
try {
// Test with a simple text search
const url = "https://places.googleapis.com/v1/places:searchText";
const headers = {
"Content-Type": "application/json",
"X-Goog-Api-Key": apiKey,
"X-Goog-FieldMask": "places.displayName,places.formattedAddress"
};
const requestBody = {
textQuery: "restaurant",
pageSize: 1
};
console.log("\nš Making test request to Google Places API...");
const response = await axios.post(url, requestBody, {
headers,
timeout: 10000
});
console.log("ā
Success! API Key is working correctly");
console.log(`š Response Status: ${response.status}`);
if (response.data && response.data.places && response.data.places.length > 0) {
const place = response.data.places[0];
console.log("šŖ Sample result:");
console.log(` Name: ${place.displayName?.text || 'N/A'}`);
console.log(` Address: ${place.formattedAddress || 'N/A'}`);
} else {
console.log("š API responded successfully but no places found");
}
console.log("\nš Your Google Places API key is configured correctly!");
} catch (error) {
console.log("\nā API Key test failed");
if (axios.isAxiosError(error)) {
const status = error.response?.status;
const errorData = error.response?.data;
console.log(`š Status Code: ${status}`);
switch (status) {
case 403:
console.log("š« Error: API key is invalid or doesn't have permission for Places API");
console.log("š” Check:");
console.log(" - API key is correct");
console.log(" - Places API is enabled in Google Cloud Console");
console.log(" - API key has proper permissions");
break;
case 400:
console.log("ā ļø Error: Bad request - API key might be missing required configuration");
break;
case 429:
console.log("ā° Error: Rate limit exceeded or quota exhausted");
break;
default:
console.log(`š Unexpected error: ${errorData?.error?.message || error.message}`);
}
if (errorData?.error?.details) {
console.log("š Error details:", JSON.stringify(errorData.error.details, null, 2));
}
} else {
console.log(`š Network error: ${error.message}`);
}
process.exit(1);
}
}
// Add helpful information
console.log("š¢ Google Places API Key Tester");
console.log("=================================");
testGooglePlacesAPI();