googleapis / google-cloud-node

Google Cloud Client Library for Node.js
https://cloud.google.com/nodejs
Apache License 2.0
2.92k stars 591 forks source link

Authenticating for @googlemaps/addressvalidation with an API key #5099

Open codan84 opened 8 months ago

codan84 commented 8 months ago

According to the docs/examples of Google Address Validation we can use an API key to authenticate:

curl -X POST -d '{
  "address": {
    "regionCode": "US",
    "locality": "Mountain View",
    "addressLines": ["1600 Amphitheatre Pkwy"]
  }
}' \
-H 'Content-Type: application/json' \
"https://addressvalidation.googleapis.com/v1:validateAddress?key=API_KEY"

https://developers.google.com/maps/documentation/address-validation/requests-validate-address

However, I can't see any reference/docs as to how I can use said API key when using SDK: https://www.npmjs.com/package/@googlemaps/addressvalidation

Nor can I see any reference to that in https://github.com/googleapis/google-auth-library-nodejs

Any clues? Or am I restricted to making http calls (fetch, axios etc) from my node app in order to achieve this?

cedvdb commented 7 months ago

@codan84 what did you end up doing ?

@sofisl did you have time to look into this ?

codan84 commented 7 months ago

I ended up using fetch and hitting your APIs directly

bshi commented 5 months ago

Nor can I see any reference to that in https://github.com/googleapis/google-auth-library-nodejs

I haven't tested this myself yet, but tracing through some of the dependencies that the client library pulls in, you can use google-auth-library to create a JWT AuthClient instance using [fromAPIKey(apiKey: string, options?: AuthClientOptions)](https://github.com/googleapis/google-auth-library-nodejs/blob/7dbedff829be093dad0a2da32f0ab12862d473bc/src/auth/googleauth.ts#L812]

This can then be injected into AddressValidationClient to override the default auth mechanisms.

const options = {
  authClient: fromAPIKey("my-api-key"),
};
const apiClient = new AddressValidationClient(options);

See also:

janvennemann commented 4 months ago

I haven't tested this myself yet, but tracing through some of the dependencies that the client library pulls in, you can use google-auth-library to create a JWT AuthClient instance

I can confirm that this works. I was looking for any easy way to move from manual HTTP requests to the new Places SDK and here is how you can create the client:

import { v1 as PlacesApiV1 } from '@googlemaps/places';
import { JWT } from 'google-auth-library';

const { PlacesClient } = PlacesApiV1;
const authClient = new JWT();
authClient.fromAPIKey('my-api-key');
const placesClient = new PlacesClient({
    authClient,
});