Resolve service

Resolve a Service Directory service.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for Service Directory, see Service Directory client libraries.

To authenticate to Service Directory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Cloud.ServiceDirectory.V1;

public class ResolveServiceSample
{
    public Service ResolveService(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId = "test-service")
    {
        // Create client
        LookupServiceClient lookupServiceClient = LookupServiceClient.Create();
        // Initialize request argument(s)
        ResolveServiceRequest request = new ResolveServiceRequest
        {
            ServiceName = ServiceName.FromProjectLocationNamespaceService(projectId, locationId, namespaceId, serviceId),
        };
        // Make the request
        ResolveServiceResponse response = lookupServiceClient.ResolveService(request);
        return response.Service;
    }
}

Go

To learn how to install and use the client library for Service Directory, see Service Directory client libraries.

To authenticate to Service Directory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "cloud.google.com/go/servicedirectory/apiv1/servicedirectorypb"
)

func resolveService(w io.Writer, projectID string) error {
	// projectID := "my-project"
	location := "us-east4"
	namespaceID := "golang-test-namespace"
	serviceID := "golang-test-service"

	ctx := context.Background()
	// Create a lookup client.
	resolver, err := servicedirectory.NewLookupClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewLookupClient: %w", err)
	}

	defer resolver.Close()
	// Now Resolve the service.
	req := &sdpb.ResolveServiceRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/namespaces/%s/services/%s", projectID, location, namespaceID, serviceID),
	}
	result, err := resolver.ResolveService(ctx, req)
	if err != nil {
		return fmt.Errorf("ResolveService: %w", err)
	}

	fmt.Fprintf(w, "Successfully Resolved Service %v\n", result)
	return nil
}

Java

To learn how to install and use the client library for Service Directory, see Service Directory client libraries.

To authenticate to Service Directory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.servicedirectory.v1.Endpoint;
import com.google.cloud.servicedirectory.v1.LookupServiceClient;
import com.google.cloud.servicedirectory.v1.ResolveServiceRequest;
import com.google.cloud.servicedirectory.v1.ResolveServiceResponse;
import com.google.cloud.servicedirectory.v1.ServiceName;
import java.io.IOException;

public class ServicesResolve {

  public static void resolveService() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // These variables should refer to an existing Service Directory service.
    String projectId = "your-project-id";
    String locationId = "your-region";
    String namespaceId = "your-namespace";
    String serviceId = "your-service";
    resolveService(projectId, locationId, namespaceId, serviceId);
  }

  // Resolve a service.
  public static void resolveService(
      String projectId, String locationId, String namespaceId, String serviceId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (LookupServiceClient client = LookupServiceClient.create()) {
      // The service to resolve.
      ServiceName name = ServiceName.of(projectId, locationId, namespaceId, serviceId);

      // Construct the resolve request to be sent to the client.
      ResolveServiceRequest request =
          ResolveServiceRequest.newBuilder().setName(name.toString()).build();

      // Send the request to resolve the service.
      ResolveServiceResponse resolveResponse = client.resolveService(request);

      // Process the response.
      System.out.println("Resolved Service: " + resolveResponse.getService().getName());

      System.out.println("Endpoints found:");
      for (Endpoint endpoint : resolveResponse.getService().getEndpointsList()) {
        System.out.println(
            endpoint.getName() + " -- " + endpoint.getAddress() + ":" + endpoint.getPort());
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Service Directory, see Service Directory client libraries.

To authenticate to Service Directory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-central1';
// const namespaceId = 'my-namespace';
// const serviceId = 'my-service';

// Imports the Google Cloud client library
const {LookupServiceClient} = require('@google-cloud/service-directory');

// Creates a client
const lookupServiceClient = new LookupServiceClient();

// Build the service name
const serviceName = lookupServiceClient.servicePath(
  projectId,
  locationId,
  namespaceId,
  serviceId
);

async function resolveService() {
  const [response] = await lookupServiceClient.resolveService({
    name: serviceName,
  });

  console.log(`Resolved service: ${response.service.name}`);
  for (const e of response.service.endpoints) {
    console.log(`\n${e.name}`);
    console.log(`Address: ${e.address}`);
    console.log(`Port: ${e.port}\n`);
  }
  return response.service;
}

return resolveService();

PHP

To learn how to install and use the client library for Service Directory, see Service Directory client libraries.

To authenticate to Service Directory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\ServiceDirectory\V1beta1\LookupServiceClient;
use Google\Cloud\ServiceDirectory\V1beta1\Service;

/**
 * @param string $projectId     Your Cloud project ID
 * @param string $locationId    Your GCP region
 * @param string $namespaceId   Your namespace name
 * @param string $serviceId     Your service name
 */
function resolve_service(
    string $projectId,
    string $locationId,
    string $namespaceId,
    string $serviceId
): void {
    // Instantiate a client.
    $client = new LookupServiceClient();

    // Run request.
    $serviceName = LookupServiceClient::serviceName($projectId, $locationId, $namespaceId, $serviceId);
    $service = $client->resolveService($serviceName)->getService();

    // Print results.
    printf('Resolved Service: %s' . PHP_EOL, $service->getName());
    print('Endpoints:' . PHP_EOL);
    foreach ($service->getEndpoints() as $endpoint) {
        printf('  Name: %s' . PHP_EOL, $endpoint->getName());
        printf('    IP: %s' . PHP_EOL, $endpoint->getAddress());
        printf('    Port: %d' . PHP_EOL, $endpoint->getPort());
    }
}

Python

To learn how to install and use the client library for Service Directory, see Service Directory client libraries.

To authenticate to Service Directory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def resolve_service(
    project_id: str, location: str, namespace_id: str, service_id: str
) -> ResolveServiceResponse:
    """Resolves a service in the given namespace.

    Args:
        project_id: Your Google Cloud project id.
        location: The Google Cloud region containing the namespace.
        namespace_id: The id of the parent namespace.
        service_id: The id of the service to resolve.

    Returns:
        The resolved service response, which returns all properties of the service, all endpoints, and all annotations.
    """

    client = servicedirectory_v1.LookupServiceClient()

    request = servicedirectory_v1.ResolveServiceRequest(
        name=servicedirectory_v1.RegistrationServiceClient().service_path(
            project_id, location, namespace_id, service_id
        )
    )

    response = client.resolve_service(request=request)

    print("Endpoints found:")
    for endpoint in response.service.endpoints:
        print(f"{endpoint.name} -- {endpoint.address}:{endpoint.port}")

    return response

Ruby

To learn how to install and use the client library for Service Directory, see Service Directory client libraries.

To authenticate to Service Directory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# project   = "Your Google Cloud project ID"
# location  = "The Google Cloud region containing the namespace"
# namespace = "The name of the parent namespace"
# service   = "The name of the service"

require "google/cloud/service_directory"

# Initialize the client
lookup_service = Google::Cloud::ServiceDirectory.lookup_service

# The name of the service
service_path = lookup_service.service_path(
  project:   project,
  location:  location,
  namespace: namespace,
  service:   service
)

# Use the Service Directory API to resolve the service
response = lookup_service.resolve_service name: service_path
puts "Resolved service: #{response.service.name}"
puts "Endpoints: "
response.service.endpoints.each do |endpoint|
  puts "#{endpoint.name} #{endpoint.address} #{endpoint.port}"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.