typescriptgoogle-places-api

How to correctly type Google Places Text Search (New) requests/Responses in Node.js/TypeScript?


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:

  1. How can I define types for the request parameters and the response from the Google Places API?
  2. Are there any existing TypeScript definitions or packages that can help with this?
  3. Is calling it like this from nodejs a valid approach? All the examples seem to be client based but I need to do it from the server.

Any guidance or examples would be greatly appreciated!


Solution

  • 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;
    }