Service Directory client libraries

Stay organized with collections Save and categorize content based on your preferences.

This page shows how to get started with the Cloud Client Libraries for the Service Directory API. Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Install the client library

C#

For more information, see Setting Up a C# Development Environment.

Using PowerShell or the Visual Studio Package Manager Console:

Install-Package "Google.Cloud.ServiceDirectory.V1" -Version "1.0.0"

Using the dotnet CLI:

dotnet add package "Google.Cloud.ServiceDirectory.V1" -Version "1.0.0"

Go

For more information, see Setting Up a Go Development Environment.

go get "cloud.google.com/go/servicedirectory/apiv1beta1"

Java

For more information, see Setting Up a Java Development Environment.

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.1.4</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-servicedirectory</artifactId>
  </dependency>

If you are using Gradle, add the following to your dependencies:

implementation platform('com.google.cloud:libraries-bom:26.1.4')

implementation 'com.google.cloud:google-cloud-servicedirectory'

If you are using sbt, add the following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-servicedirectory" % "2.6.0"

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install @google-cloud/service-directory

PHP

For more information, see Using PHP on Google Cloud.

composer require google/cloud-service-directory

Python

For more information, see Setting Up a Python Development Environment.

pip install google-cloud-service-directory

Ruby

For more information, see Setting Up a Ruby Development Environment.

gem install google-cloud-service_directory

Set up authentication

When you use client libraries, you use Application Default Credentials (ADC) to authenticate. For information about setting up ADC, see Provide credentials for Application Default Credentials. For information about using ADC with client libraries, see Authenticate using client libraries.

Use the client library

The following example shows how to use the client library.

Go

To learn how to install and use the client library for Service Directory, see Service Directory client libraries. For more information, see the Service Directory Go API reference documentation.


// Sample quickstart is a program that uses Cloud Service Directory
// create. delete, and resolve functionality.
package main

import (
	"context"
	"fmt"
	"log"

	servicedirectory "cloud.google.com/go/servicedirectory/apiv1"
	sdpb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1"
)

func main() {
	projectID := "your-project-id"
	location := "us-west1"
	serviceID := "golang-quickstart-service"
	namespaceID := "golang-quickstart-namespace"
	endpointID := "golang-quickstart-endpoint"

	ctx := context.Background()
	// Create a registration client.
	registry, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		log.Fatalf("servicedirectory.NewRegistrationClient: %v", err)
	}
	defer registry.Close()

	// Create a lookup client.
	resolver, err := servicedirectory.NewLookupClient(ctx)
	if err != nil {
		log.Fatalf("servicedirectory.NewLookupClient: %v", err)
	}
	defer resolver.Close()

	// Create a Namespace.
	createNsReq := &sdpb.CreateNamespaceRequest{
		Parent:      fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		NamespaceId: namespaceID,
	}
	namespace, err := registry.CreateNamespace(ctx, createNsReq)
	if err != nil {
		log.Fatalf("servicedirectory.CreateNamespace: %v", err)
	}

	// Create a Service.
	createServiceReq := &sdpb.CreateServiceRequest{
		Parent:    namespace.Name,
		ServiceId: serviceID,
		Service: &sdpb.Service{
			Annotations: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
		},
	}
	service, err := registry.CreateService(ctx, createServiceReq)
	if err != nil {
		log.Fatalf("servicedirectory.CreateService: %v", err)
	}

	// Create an Endpoint.
	createEndpointReq := &sdpb.CreateEndpointRequest{
		Parent:     service.Name,
		EndpointId: endpointID,
		Endpoint: &sdpb.Endpoint{
			Address: "8.8.8.8",
			Port:    8080,
			Annotations: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
		},
	}
	_, err = registry.CreateEndpoint(ctx, createEndpointReq)
	if err != nil {
		log.Fatalf("servicedirectory.CreateEndpoint: %v", err)
	}

	// Now Resolve the service.
	lookupRequest := &sdpb.ResolveServiceRequest{
		Name: service.Name,
	}
	result, err := resolver.ResolveService(ctx, lookupRequest)
	if err != nil {
		log.Fatalf("servicedirectory.ResolveService: %v", err)
		return
	}

	fmt.Printf("Successfully Resolved Service %v", result)

	// Delete the namespace.
	deleteNsReq := &sdpb.DeleteNamespaceRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/namespaces/%s",
			projectID, location, namespaceID),
	}
	registry.DeleteNamespace(ctx, deleteNsReq) // Ignore results.
}

Java

To learn how to install and use the client library for Service Directory, see Service Directory client libraries. For more information, see the Service Directory Java API reference documentation.


import com.google.cloud.servicedirectory.v1.LocationName;
import com.google.cloud.servicedirectory.v1.Namespace;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient.ListNamespacesPagedResponse;
import java.io.IOException;

public class Quickstart {

  public static void quickstart() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "your-region";
    quickstart(projectId, locationId);
  }

  public static void quickstart(String projectId, String locationId) 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 (RegistrationServiceClient client = RegistrationServiceClient.create()) {

      // The project and location that hold the namespace to list.
      LocationName parent = LocationName.of(projectId, locationId);

      // Call the API.
      ListNamespacesPagedResponse response = client.listNamespaces(parent);

      // Iterate over each namespace and print its name.
      System.out.println("Namespaces:");
      for (Namespace namespace : response.iterateAll()) {
        System.out.println(namespace.getName());
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Service Directory, see Service Directory client libraries. For more information, see the Service Directory Node.js API reference documentation.

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

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

// Creates a client
const registrationServiceClient = new RegistrationServiceClient();

// Build the location name
const locationName = registrationServiceClient.locationPath(
  projectId,
  locationId
);

async function listNamespaces() {
  const [namespaces] = await registrationServiceClient.listNamespaces({
    parent: locationName,
  });

  console.log('Namespaces: ');
  for (const n of namespaces) {
    console.log(`${n.name}`);
  }
  return namespaces;
}

return listNamespaces();

PHP

To learn how to install and use the client library for Service Directory, see Service Directory client libraries. For more information, see the Service Directory PHP API reference documentation.

use Google\Cloud\ServiceDirectory\V1beta1\RegistrationServiceClient;

/** Uncomment and populate these variables in your code */
// $projectId = '[YOUR_PROJECT_ID]';
// $locationId = '[YOUR_GCP_REGION]';

// Instantiate a client.
$client = new RegistrationServiceClient();

// Run request.
$locationName = RegistrationServiceClient::locationName($projectId, $locationId);
$pagedResponse = $client->listNamespaces($locationName);

// Iterate over each namespace and print its name.
print('Namespaces: ' . PHP_EOL);
foreach ($pagedResponse->iterateAllElements() as $namespace) {
    print($namespace->getName() . PHP_EOL);
}

Python

To learn how to install and use the client library for Service Directory, see Service Directory client libraries. For more information, see the Service Directory Python API reference documentation.

from google.cloud import servicedirectory_v1


def list_namespaces(project_id, location_id):
    """Lists all namespaces in the given location."""

    client = servicedirectory_v1.RegistrationServiceClient()

    response = client.list_namespaces(
        parent=f'projects/{project_id}/locations/{location_id}')

    print(f'Listed namespaces in {location_id}.')
    for namespace in response:
        print(f'Namespace: {namespace.name}')

    return response

Ruby

To learn how to install and use the client library for Service Directory, see Service Directory client libraries. For more information, see the Service Directory Ruby API reference documentation.

# Imports the Google Cloud client library
require "google/cloud/service_directory"

# Your Google Cloud Platform project ID
project = ENV["GOOGLE_CLOUD_PROJECT"]

# Location of the Service Directory Namespace
location = "us-central1"

# Initialize a client
registration_service = Google::Cloud::ServiceDirectory.registration_service

# The resource name of the project
location_name = registration_service.location_path(
  project: project, location: location
)

# Request list of namespaces in the project
response = registration_service.list_namespaces parent: location_name

# List all namespaces for your project
puts "Namespaces: "
response.each do |namespace|
  puts namespace.name
end

Next steps

Learn how to programmatically configure Service Directory.

Additional resources