Create service

Create 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 CreateServiceSample
{
    public Service CreateService(
        string projectId = "my-project",
        string locationId = "us-east1",
        string namespaceId = "test-namespace",
        string serviceId = "test-service")
    {
        // Create client
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        // Initialize request argument(s)
        var namespaceName = NamespaceName.FromProjectLocationNamespace(projectId, locationId, namespaceId);
        return registrationServiceClient.CreateService(namespaceName, new Service(), serviceId);
    }
}


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 createService(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 registration client.
	client, err := servicedirectory.NewRegistrationClient(ctx)
	if err != nil {
		return fmt.Errorf("ServiceDirectory.NewRegistrationClient: %w", err)
	}

	defer client.Close()
	// Create a Service.
	req := &sdpb.CreateServiceRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s/namespaces/%s", projectID, location, namespaceID),
		ServiceId: serviceID,
		Service: &sdpb.Service{
			Annotations: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
		},
	}
	service, err := client.CreateService(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateSerice: %w", err)
	}
	fmt.Fprintf(w, "servicedirectory.Createservice result %s\n", service.Name)
	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.NamespaceName;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
import com.google.cloud.servicedirectory.v1.Service;
import java.io.IOException;

public class ServicesCreate {

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

  // Create a new service.
  public static void createService(
      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 (RegistrationServiceClient client = RegistrationServiceClient.create()) {

      // The namespace to create the service in.
      NamespaceName parent = NamespaceName.of(projectId, locationId, namespaceId);

      // The service object to create.
      // Optionally add some annotations for the service.
      Service service = Service.newBuilder().putAnnotations("protocol", "tcp").build();

      // Send the request to create the namespace.
      Service createdService = client.createService(parent, service, serviceId);

      // Process the response.
      System.out.println("Created Service: " + createdService.getName());
      System.out.println("Annotations: " + createdService.getAnnotationsMap());
    }
  }
}

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

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

// Build the namespace name
const namespaceName = registrationServiceClient.namespacePath(
  projectId,
  locationId,
  namespaceId
);

async function createService() {
  const [service] = await registrationServiceClient.createService({
    parent: namespaceName,
    serviceId: serviceId,
  });

  console.log(`Created service: ${service.name}`);
  return service;
}

return createService();

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\RegistrationServiceClient;
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 create_service(
    string $projectId,
    string $locationId,
    string $namespaceId,
    string $serviceId
): void {
    // Instantiate a client.
    $client = new RegistrationServiceClient();

    // Run request.
    $namespaceName = RegistrationServiceClient::namespaceName($projectId, $locationId, $namespaceId);
    $service = $client->createService($namespaceName, $serviceId, new Service());

    // Print results.
    printf('Created Service: %s' . PHP_EOL, $service->getName());
}

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 create_service(
    project_id: str, location: str, namespace_id: str, service_id: str
) -> Service:
    """Creates 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 you are creating. Service names must be unique within a namespace and follow
            conventions for DNS labels.

    Returns:
        The created service.
    """

    client = servicedirectory_v1.RegistrationServiceClient()

    service = servicedirectory_v1.Service(
        name=client.service_path(project_id, location, namespace_id, service_id)
    )

    response = client.create_service(
        parent=client.namespace_path(project_id, location, namespace_id),
        service=service,
        service_id=service_id,
    )

    print(f"Created service {response.name}.")

    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 you are creating"

require "google/cloud/service_directory"

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

# The parent path of the service
parent = registration_service.namespace_path(
  project: project, location: location, namespace: namespace
)

# Use the Service Directory API to create the service
response = registration_service.create_service parent: parent, service_id: service
puts "Created service: #{response.name}"

What's next

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