Create workflow (v1)

Create a new workflow in a given project and location.

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Workflows quickstart using client libraries. For more information, see the Workflows Go API reference documentation.

To authenticate to Workflows, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"

	workflows "cloud.google.com/go/workflows/apiv1"
	workflowspb "cloud.google.com/go/workflows/apiv1/workflowspb"
)

// createWorkflow creates a workflow in a given project and location.
func createWorkflow(ctx context.Context, w io.Writer, projectID string, locationID string, workflowID string) error {
	client, err := workflows.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("workflows.NewClient: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
	workflow := &workflowspb.Workflow{
		Description: "Example workflow",
		SourceCode: &workflowspb.Workflow_SourceContents{
			SourceContents: "main:\n  steps:\n    - init:\n        assign:\n          - message: \"Hello World!\"\n    - returnResult:\n        return: ${message}",
		},
	}

	req := &workflowspb.CreateWorkflowRequest{
		Parent:     parent,
		WorkflowId: workflowID,
		Workflow:   workflow,
	}

	op, err := client.CreateWorkflow(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateWorkflow: %w", err)
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Created workflow: %s\n", resp.GetName())
	return nil
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Workflows quickstart using client libraries. For more information, see the Workflows Node.js API reference documentation.

To authenticate to Workflows, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {WorkflowsClient} = require('@google-cloud/workflows');
const {status} = require('@grpc/grpc-js');

const client = new WorkflowsClient();

/**
 * Use the createWorkflow method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} locationId - The Google Cloud region where the service is located (for example, 'us-central1')
 * @param {string} workflowId - ID of the Workflow (for example, 'example-workflow-id')
 */
async function createWorkflow(projectId, locationId, workflowId) {
  try {
    const parent = client.locationPath(projectId, locationId);
    const workflow = {
      description: 'Example workflow',
      sourceContents: 'main:\n  steps:\n    - returnStep:\n        return: "Hello, World!"',
    };

    const [operation] = await client.createWorkflow({
      parent,
      workflow,
      workflowId,
    });

    const [response] = await operation.promise();
    console.log(`Created workflow: ${response.name}`);
    console.log(`State: ${response.state}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Workflow ${workflowId} already exists:`, err.message);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error('Permission denied while creating workflow:', err.message);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error('Invalid argument provided:', err.message);
    } else {
      console.error('Unexpected error creating workflow:', err);
    }
  }
}

module.exports = { createWorkflow };

Python

Before trying this sample, follow the Python setup instructions in the Workflows quickstart using client libraries. For more information, see the Workflows Python API reference documentation.

To authenticate to Workflows, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import google.api_core.exceptions
from google.cloud import workflows_v1

client = workflows_v1.WorkflowsClient()


def create_workflow(project_id: str, location_id: str, workflow_id: str) -> None:
    """Use the create_workflow method

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id')
        location_id: The Google Cloud region where the service is located (for example, 'us-central1')
        workflow_id: ID of the Workflow (for example, 'example-workflow-id')
    """
    parent = f"projects/{project_id}/locations/{location_id}"
    workflow = workflows_v1.Workflow(
        description="Example workflow created with the Workflows API.",
        source_contents=(
            "main:\n"
            "  steps:\n"
            "    - init:\n"
            "        assign:\n"
            "          - message: 'Workflow initialized successfully'\n"
            "    - returnOutput:\n"
            "        return: ${message}\n"
        ),
    )

    try:
        # Initiate the long-running operation to create the workflow
        operation = client.create_workflow(
            parent=parent,
            workflow=workflow,
            workflow_id=workflow_id,
        )
        response = operation.result()
        print(f"Created workflow: {response.name}")
        print(f"Workflow state: {response.state.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create workflow: {error}")

What's next

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