Service Directory client libraries

This page shows how to get started with the Cloud Client Libraries for the Service Directory API. Client libraries make it easier to access Google Cloud APIs from a supported language. Although you can use Google Cloud APIs directly by making raw requests to the server, client libraries provide simplifications that significantly reduce the amount of code you need to write.

Read more about the Cloud Client Libraries and the older Google API Client Libraries in Client libraries explained.

Install the client library


See Setting up a C++ development environment for details about this client library's requirements and install dependencies.


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"

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


go get ""

For more information, see Setting Up a Go 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:

implementation ''

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

libraryDependencies += "" % "google-cloud-servicedirectory" % "2.42.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.

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


npm install @google-cloud/service-directory

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


composer require google/cloud-service-directory

For more information, see Using PHP on Google Cloud.


pip install google-cloud-service-directory

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


gem install google-cloud-service_directory

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

Set up authentication

To authenticate calls to Google Cloud APIs, client libraries support Application Default Credentials (ADC); the libraries look for credentials in a set of defined locations and use those credentials to authenticate requests to the API. With ADC, you can make credentials available to your application in a variety of environments, such as local development or production, without needing to modify your application code.

For production environments, the way you set up ADC depends on the service and context. For more information, see Set up Application Default Credentials.

For a local development environment, you can set up ADC with the credentials that are associated with your Google Account:

  1. Install and initialize the gcloud CLI.

    When you initialize the gcloud CLI, be sure to specify a Google Cloud project in which you have permission to access the resources your application needs.

  2. Create your credential file:

    gcloud auth application-default login

    A sign-in screen appears. After you sign in, your credentials are stored in the local credential file used by ADC.

Use the client library

The following example shows how to use the client library.


#include "google/cloud/servicedirectory/v1/registration_client.h"
#include "google/cloud/location.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " project-id location-id\n";
    return 1;

  auto const location = google::cloud::Location(argv[1], argv[2]);

  namespace servicedirectory = ::google::cloud::servicedirectory_v1;
  auto client = servicedirectory::RegistrationServiceClient(

  for (auto ns : client.ListNamespaces(location.FullName())) {
    if (!ns) throw std::move(ns).status();
    std::cout << ns->DebugString() << "\n";

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;


// 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)
	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: "",
			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)

	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.



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


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


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


from import servicedirectory_v1
from import (

def list_namespaces(project_id: str, location: str) -> ListNamespacesPager:
    """Lists all namespaces in the given location.

        project_id: The Google Cloud project id.
        location: The location which contains the namespaces to list.

        All namespaces in the given location.

    client = servicedirectory_v1.RegistrationServiceClient()

    response = client.list_namespaces(

    print(f"Listed namespaces in {location}.")
    for namespace in response:
        print(f"Namespace: {}")

    return response


# 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


The following list contains links to more resources related to the client library for C++:


The following list contains links to more resources related to the client library for C#:


The following list contains links to more resources related to the client library for Go:


The following list contains links to more resources related to the client library for Java:


The following list contains links to more resources related to the client library for Node.js:


The following list contains links to more resources related to the client library for PHP:


The following list contains links to more resources related to the client library for Python:


The following list contains links to more resources related to the client library for Ruby: