Service Directory Client Libraries

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.

Installing the client library


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

go get -u ""


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.



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

compile ''

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

libraryDependencies += "" % "google-cloud-servicedirectory" % "0.2.6"

If you're using 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.


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

npm install @google-cloud/service-directory


For more information, see Using PHP on Google Cloud.

composer require google/cloud-service-directory


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

pip install google-cloud-service-directory


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

gem install google-cloud-service_directory

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console

  1. In the Cloud Console, go to the Create service account key page.

    Go to the Create Service Account Key page
  2. From the Service account list, select New service account.
  3. In the Service account name field, enter a name.
  4. From the Role list, select Project > Owner.

  5. Click Create. A JSON file that contains your key downloads to your computer.

Command line

You can run the following commands using the Cloud SDK on your local machine, or in Cloud Shell.

  1. Create the service account. Replace NAME with a name for the service account.

    gcloud iam service-accounts create NAME
  2. Grant permissions to the service account. Replace PROJECT_ID with your project ID.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="" --role="roles/owner"
  3. Generate the key file. Replace FILE_NAME with a name for the key file.

    gcloud iam service-accounts keys create FILE_NAME.json

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS


For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"


With PowerShell:


For example:


With command prompt:


Using the client library

The following example shows how to use the client library.


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 (

	servicedirectory ""
	sdpb ""

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)

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

	// 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{
			Metadata: 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: "",
			Port:    8080,
			Metadata: 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)

	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.


For more information, see the Service Directory Java API reference documentation.


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.
      for (Namespace namespace : response.iterateAll()) {


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 {
} = require('@google-cloud/service-directory');

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

// Build the location name
const locationName = registrationServiceClient.locationPath(

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

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

return listNamespaces();


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


For more information, see the Service Directory Python API reference documentation.

from import servicedirectory_v1beta1

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

    client = servicedirectory_v1beta1.RegistrationServiceClient()

    response = client.list_namespaces(

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

    return response


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

# 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|

Next steps

Learn how to programmatically configure Service Directory.

Additional resources