Quickstart

Basic usage of the Service Directory client library.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

Go

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


// 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.


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.

//
// 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.

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.

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.

# 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

What's next

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