Exemplos de biblioteca de cliente da API Address Validation

Esta página tem exemplos de como usar as bibliotecas de cliente da API Address Validation para chamar os seguintes serviços:

Instalar as bibliotecas de cliente

Consulte Bibliotecas de cliente da API Address Validation para ver instruções de instalação.

Autenticação

Com as bibliotecas de cliente, você usa o Application Default Credentials (ADC) para autenticação. Para informações sobre como configurar o ADC, consulte Fornecer credenciais para o Application Default Credentials. Para informações sobre como usar o ADC com bibliotecas de cliente, consulte Autenticar usando bibliotecas de cliente.

Também é possível usar chaves de API para autenticar nas bibliotecas de cliente, por exemplo:

using Google.Maps.AddressValidation.V1;
using Google.Api.Gax.Grpc;
using Grpc.Core;
...
// Create settings to pass the API key as a header in every request.
var apiHeader = CallSettings.FromHeader("X-Goog-Api-Key", "API_KEY");
var defaultSettings = AddressValidationSettings.GetDefault();
var settings = new AddressValidationSettings
{
    ValidateAddressSettings = defaultSettings.ValidateAddressSettings.MergedWith(apiHeader),
    ProvideValidationFeedbackSettings = defaultSettings.ProvideValidationFeedbackSettings.MergedWith(apiHeader)
};
// Create a client builder with the custom settings.
AddressValidationClientBuilder builder = new AddressValidationClientBuilder
{
    Settings = settings,
    // Use SslCredentials to create a secure channel for API key authentication.
    ChannelCredentials = new SslCredentials()
};
AddressValidationClient client = await builder.BuildAsync();

Ao usar chaves de API nos seus aplicativos, garanta que elas sejam mantidas em segurança durante o armazenamento e a transmissão. A exposição pública das chaves de API pode levar a cobranças inesperadas na sua conta.

Os exemplos nesta página usam o Application Default Credentials.

Exemplos

validateAddress

Confira a seguir um exemplo de como chamar validateAddress usando a biblioteca de cliente.

using Google.Maps.AddressValidation.V1;
using Google.Type;
...
private static async Task CallAddressValidation()
{
    // Create the Address Validation Client
    AddressValidationClient client = await AddressValidationClient.CreateAsync();
    // Define the request with the address to be validated
    var request = new ValidateAddressRequest
    {
        Address = new PostalAddress
        {
            RegionCode = "US",
            LanguageCode = "en",
            PostalCode = "94043",
            AdministrativeArea = "CA",
            Locality = "Mountain View",
            AddressLines = { "1600 Amphitheatre Parkway" }
        }
    };
    try
    {
        // Call the API asynchronously
        ValidateAddressResponse response = await client.ValidateAddressAsync(request);
        // Process the results
        Console.WriteLine($"Validation Granularity: {response.Result.Verdict.ValidationGranularity}");
        Console.WriteLine($"Formatted Address: {response.Result.Address.FormattedAddress}");
        Console.WriteLine($"Response ID: {response.ResponseId}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}

Defina um objeto PostalAddress com campos de endereços divididos em componentes, como RegionCode, Locality e AddressLines. Ao criar a solicitação de exemplo, essa PostalAddress é usada para criar uma ValidateAddressRequest. O método ValidateAddressAsync é chamado para fazer a solicitação, e os detalhes da resposta, como ValidationGranularity e FormattedAddress, são gerados.

provideValidationFeedback

Confira a seguir um exemplo de como chamar provideValidationFeedback usando a biblioteca de cliente.

using Google.Maps.AddressValidation.V1;
...
private static async Task ProvideValidationFeedback()
{
    AddressValidationClient client = await AddressValidationClient.CreateAsync();

    var feedbackRequest = new ProvideValidationFeedbackRequest
    {
        // Set the conclusion based on the user's choice. This exampels uses ValidatedVersionUsed
        Conclusion = ProvideValidationFeedbackRequest.Types.ValidationConclusion.ValidatedVersionUsed,
        // Provide the ID from the validation response.
        ResponseId = "Response_ID"
    };
    try
    {
        Console.WriteLine("Sending feedback to the API");
        // This call returns an empty response on success.
        await client.ProvideValidationFeedbackAsync(feedbackRequest);
        Console.WriteLine(" -> Feedback sent successfully!");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}

Crie um ProvideValidationFeedbackRequest para enviar informações sobre o resultado final de uma sequência de validação de endereço. A solicitação exige um Conclusion para especificar se o endereço original do usuário ou o endereço validado do Google foi usado. É fundamental que você também forneça o ResponseId recebido do ValidateAddressResponse inicial para vincular o feedback à transação correta.