Address Validation API 클라이언트 라이브러리 예시

이 페이지에는 Address Validation API 클라이언트 라이브러리를 사용하여 다음 서비스를 호출하는 방법의 예가 나와 있습니다.

클라이언트 라이브러리 설치

설치 안내는 Address Validation API 클라이언트 라이브러리를 참고하세요.

인증

클라이언트 라이브러리를 사용할 때는 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하여 인증합니다. ADC 설정에 관한 자세한 내용은 애플리케이션 기본 사용자 인증 정보에 대한 사용자 인증 정보 제공을 참고하세요. 클라이언트 라이브러리에서 ADC를 사용하는 방법은 클라이언트 라이브러리를 사용하여 인증을 참고하세요.

API 키를 사용하여 클라이언트 라이브러리에 인증할 수도 있습니다. 예를 들면 다음과 같습니다.

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();

애플리케이션에서 API 키를 사용하는 경우 저장 및 전송 중에 안전하게 보호되도록 해야 합니다. API 키를 공개적으로 노출하면 계정에 예상치 않은 비용이 부과될 수 있습니다.

이 페이지의 예에서는 애플리케이션 기본 사용자 인증 정보를 사용합니다.

validateAddress

다음은 클라이언트 라이브러리를 사용하여 validateAddress를 호출하는 방법의 예입니다.

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}");
    }
}

RegionCode, Locality, AddressLines와 같은 구성요소화된 주소 필드가 있는 PostalAddress 객체를 정의합니다. 예시 요청을 빌드할 때 이 PostalAddressValidateAddressRequest를 만드는 데 사용됩니다. 그런 다음 ValidateAddressAsync 메서드가 호출되어 요청을 실행하고 ValidationGranularityFormattedAddress와 같은 응답의 세부정보가 출력됩니다.

provideValidationFeedback

다음은 클라이언트 라이브러리를 사용하여 provideValidationFeedback를 호출하는 방법의 예입니다.

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}");
    }
}

주소 검증 시퀀스의 최종 결과에 관한 정보를 전송하는 ProvideValidationFeedbackRequest를 만듭니다. 요청에는 Conclusion가 사용자의 원래 주소 또는 Google에서 확인한 주소가 사용되었는지 지정해야 합니다. 또한 피드백을 올바른 거래에 연결하려면 초기 ValidateAddressResponse에서 가져온 ResponseId도 제공해야 합니다.