I’m working on a Node.js application using TypeScript, and I’m trying to integrate Google Places Text Search (New) API. I'm trying to ensure that my requests are properly typed but I am having trouble incorporating types.
Here’s a basic example of what I currently have:
import axios from 'axios';
const apiKey = 'MY_API_KEY';
const endpoint = `https://places.googleapis.com/v1/places:searchText`;
async function searchPlaces(query: string) {
const payload = { textQuery: query };
const response = await axios.post(endpoint, payload, {
headers: {
'Content-Type': 'application/json',
'X-Goog-Api-Key': apiKey,
'X-Goog-FieldMask': '*',
},
});
return response.data;
}
I’d like to know:
Any guidance or examples would be greatly appreciated!
I came across what seems an official API client package: https://www.npmjs.com/package/@googlemaps/places. To authenticate to it you should use google-auth-library
.
I usually go at this by beginning searching the official NPM package registry like so: https://www.npmjs.com/search?q=Google%20Places%20API. In this case I skipped over React-bound packages, the offical Google package was the first one after.
This code should work with your example (untested):
import { PlacesClient } from "@googlemaps/places";
import { GoogleAuth } from "google-auth-library";
const apiKey = "MY_API_KEY";
const authClient = new GoogleAuth().fromAPIKey(apiKey);
const placesClient = new PlacesClient({
authClient,
});
async function searchPlaces(query: string) {
const payload = { textQuery: query };
const [ response ] = await placesClient.searchText(payload, {
otherArgs: {
headers: {
"X-Goog-FieldMask": "*",
},
},
});
return response.places;
}