Execute a workflow by using client libraries

You can execute a workflow and view the execution results using a client library.

For more information about installing the client libraries and setting up your development environment, see the Workflows client libraries overview.

Before you begin

Security constraints defined by your organization might prevent you from completing the following steps. For troubleshooting information, see Develop applications in a constrained Google Cloud environment.

  1. The following sample assumes you have already deployed the workflow, myFirstWorkflow. If you haven't, deploy it now using the Google Cloud console or the Google Cloud CLI.
  2. Download and install the Git source code management tool.

Get the sample code

  1. Clone the sample app repository to your local machine:


    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.


    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.


    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

  2. Change to the directory that contains the Workflows sample code:


    cd java-docs-samples/workflows/cloud-client/


    cd nodejs-docs-samples/workflows/quickstart/


    cd python-docs-samples/workflows/cloud-client/

  3. Take a look at the sample code:


    // Imports the Google Cloud client library
    import com.google.cloud.workflows.executions.v1.CreateExecutionRequest;
    import com.google.cloud.workflows.executions.v1.Execution;
    import com.google.cloud.workflows.executions.v1.ExecutionsClient;
    import com.google.cloud.workflows.executions.v1.WorkflowName;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    public class WorkflowsQuickstart {
      private static final String PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT");
      private static final String LOCATION = System.getenv().getOrDefault("LOCATION", "us-central1");
      private static final String WORKFLOW =
          System.getenv().getOrDefault("WORKFLOW", "myFirstWorkflow");
      public static void main(String... args)
          throws IOException, InterruptedException, ExecutionException {
        if (PROJECT == null) {
          throw new IllegalArgumentException(
              "Environment variable 'GOOGLE_CLOUD_PROJECT' is required to run this quickstart.");
        workflowsQuickstart(PROJECT, LOCATION, WORKFLOW);
      private static volatile boolean finished;
      public static void workflowsQuickstart(String projectId, String location, String workflow)
          throws IOException, InterruptedException, ExecutionException {
        // 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 (ExecutionsClient executionsClient = ExecutionsClient.create()) {
          // Construct the fully qualified location path.
          WorkflowName parent = WorkflowName.of(projectId, location, workflow);
          // Creates the execution object.
          CreateExecutionRequest request =
          Execution response = executionsClient.createExecution(request);
          String executionName = response.getName();
          System.out.printf("Created execution: %s%n", executionName);
          long backoffTime = 0;
          long backoffDelay = 1_000; // Start wait with delay of 1,000 ms
          final long backoffTimeout = 10 * 60 * 1_000; // Time out at 10 minutes
          System.out.println("Poll for results...");
          // Wait for execution to finish, then print results.
          while (!finished && backoffTime < backoffTimeout) {
            Execution execution = executionsClient.getExecution(executionName);
            finished = execution.getState() != Execution.State.ACTIVE;
            // If we haven't seen the results yet, wait.
            if (!finished) {
              System.out.println("- Waiting for results");
              backoffTime += backoffDelay;
              backoffDelay *= 2; // Double the delay to provide exponential backoff.
            } else {
              System.out.println("Execution finished with state: " + execution.getState().name());
              System.out.println("Execution results: " + execution.getResult());


    const {ExecutionsClient} = require('@google-cloud/workflows');
    const client = new ExecutionsClient();
     * TODO(developer): Uncomment these variables before running the sample.
    // const projectId = 'my-project';
    // const location = 'us-central1';
    // const workflow = 'myFirstWorkflow';
    // const searchTerm = '';
     * Executes a Workflow and waits for the results with exponential backoff.
     * @param {string} projectId The Google Cloud Project containing the workflow
     * @param {string} location The workflow location
     * @param {string} workflow The workflow name
     * @param {string} searchTerm Optional search term to pass to the Workflow as a runtime argument
    async function executeWorkflow(projectId, location, workflow, searchTerm) {
       * Sleeps the process N number of milliseconds.
       * @param {Number} ms The number of milliseconds to sleep.
      function sleep(ms) {
        return new Promise(resolve => {
          setTimeout(resolve, ms);
      const runtimeArgs = searchTerm ? {searchTerm: searchTerm} : {};
      // Execute workflow
      try {
        const createExecutionRes = await client.createExecution({
          parent: client.workflowPath(projectId, location, workflow),
          execution: {
            // Runtime arguments can be passed as a JSON string
            argument: JSON.stringify(runtimeArgs),
        const executionName = createExecutionRes[0].name;
        console.log(`Created execution: ${executionName}`);
        // Wait for execution to finish, then print results.
        let executionFinished = false;
        let backoffDelay = 1000; // Start wait with delay of 1,000 ms
        console.log('Poll every second for result...');
        while (!executionFinished) {
          const [execution] = await client.getExecution({
            name: executionName,
          executionFinished = execution.state !== 'ACTIVE';
          // If we haven't seen the result yet, wait a second.
          if (!executionFinished) {
            console.log('- Waiting for results...');
            await sleep(backoffDelay);
            backoffDelay *= 2; // Double the delay to provide exponential backoff.
          } else {
            console.log(`Execution finished with state: ${execution.state}`);
            return execution.result;
      } catch (e) {
        console.error(`Error executing workflow: ${e}`);
    executeWorkflow(projectId, location, workflowName, searchTerm).catch(err => {
      process.exitCode = 1;


    import time
    from google.cloud import workflows_v1
    from google.cloud.workflows import executions_v1
    from google.cloud.workflows.executions_v1 import Execution
    from google.cloud.workflows.executions_v1.types import executions
    def execute_workflow(
        project: str, location: str = "us-central1", workflow: str = "myFirstWorkflow"
    ) -> Execution:
        """Execute a workflow and print the execution results.
        A workflow consists of a series of steps described using the Workflows syntax, and can be written in either YAML or JSON.
            project: The Google Cloud project id which contains the workflow to execute.
            location: The location for the workflow
            workflow: The ID of the workflow to execute.
            The execution response.
        # Set up API clients.
        execution_client = executions_v1.ExecutionsClient()
        workflows_client = workflows_v1.WorkflowsClient()
        # Construct the fully qualified location path.
        parent = workflows_client.workflow_path(project, location, workflow)
        # Execute the workflow.
        response = execution_client.create_execution(request={"parent": parent})
        print(f"Created execution: {response.name}")
        # Wait for execution to finish, then print results.
        execution_finished = False
        backoff_delay = 1  # Start wait with delay of 1 second
        print("Poll for result...")
        while not execution_finished:
            execution = execution_client.get_execution(request={"name": response.name})
            execution_finished = execution.state != executions.Execution.State.ACTIVE
            # If we haven't seen the result yet, wait a second.
            if not execution_finished:
                print("- Waiting for results...")
                # Double the delay to provide exponential backoff.
                backoff_delay *= 2
                print(f"Execution finished with state: {execution.state.name}")
                print(f"Execution results: {execution.result}")
                return execution

The program does the following:

  1. Sets up the Cloud Client Libraries for Workflows.
  2. Executes a workflow.
  3. Polls the workflow's execution (using exponential backoff) until the execution terminates.
  4. Prints the execution results.

Run the sample

  1. To run the sample, first install dependencies:


    mvn compile


    npm install


    pip3 install -r requirements.txt

  2. Run the script:


    GOOGLE_CLOUD_PROJECT=PROJECT_ID LOCATION=CLOUD_REGION WORKFLOW=WORKFLOW_NAME mvn compile exec:java -Dexec.mainClass=com.example.workflows.WorkflowsQuickstart





    Replace the following:

    • PROJECT_ID: (required) the Project ID of the Google Cloud project
    • CLOUD_REGION: the location for the workflow (default: us-central1)
    • WORKFLOW_NAME: the ID of the workflow (default: myFirstWorkflow)

    The output is similar to the following:

    Execution finished with state: SUCCEEDED
    ["Sunday","Sunday in the Park with George","Sunday shopping","Sunday Bloody Sunday","Sunday Times Golden Globe Race","Sunday All Stars","Sunday Night (South Korean TV series)","Sunday Silence","Sunday Without God","Sunday Independent (Ireland)"]

Pass data in an execution request

Depending on the client library language, you can also pass a runtime argument in an execution request.

For example, using JavaScript:

// Execute workflow
try {
  const createExecutionRes = await client.createExecution({
    parent: client.workflowPath(projectId, location, workflow),
    execution: {
      argument: JSON.stringify({"searchTerm": "Friday"})
const executionName = createExecutionRes[0].name;

Or, using Java:

// Creates the execution object.
CreateExecutionRequest request =

For more information about passing runtime arguments, see Pass runtime arguments in an execution request.

Clean up

To avoid incurring charges to your Google Cloud account for the resources used on this page, follow these steps.

  1. In the Google Cloud console, go to the Workflows page.

    Go to Workflows

  2. From the list of workflows, click a workflow to go to its Workflow details page.

  3. Click Delete.

  4. Type the name of the workflow and then click Confirm.

What's next