#!/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();