Using the Client Libraries

This page shows you how to get started with the Cloud Optimization API in your favorite programming language.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Optimization API.

    Enable the API

  5. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the Project > Owner role to the service account.

      To grant the role, find the Select a role list, then select Project > Owner.

    6. Click Continue.
    7. Click Done to finish creating the service account.

      Do not close your browser window. You will use it in the next step.

  6. Create a service account key:

    1. In the Google Cloud console, click the email address for the service account that you created.
    2. Click Keys.
    3. Click Add key, and then click Create new key.
    4. Click Create. A JSON key file is downloaded to your computer.
    5. Click Close.
  7. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file that contains your credentials. This variable applies only to your current shell session, so if you open a new session, set the variable again.

  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  9. Make sure that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Optimization API.

    Enable the API

  11. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the Project > Owner role to the service account.

      To grant the role, find the Select a role list, then select Project > Owner.

    6. Click Continue.
    7. Click Done to finish creating the service account.

      Do not close your browser window. You will use it in the next step.

  12. Create a service account key:

    1. In the Google Cloud console, click the email address for the service account that you created.
    2. Click Keys.
    3. Click Add key, and then click Create new key.
    4. Click Create. A JSON key file is downloaded to your computer.
    5. Click Close.
  13. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file that contains your credentials. This variable applies only to your current shell session, so if you open a new session, set the variable again.

Install the client library

C++

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

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

Java

For more on setting up your Java development environment, refer to the Java Development Environment Setup Guide.

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.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.51.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-optimization</artifactId>
  </dependency>
</dependencies>

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

implementation 'com.google.cloud:google-cloud-optimization:1.52.0'

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

libraryDependencies += "com.google.cloud" % "google-cloud-optimization" % "1.52.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.

Python

For more on setting up your Python development environment, refer to the Python Development Environment Setup Guide.

pip install --upgrade google-cloud-optimization

Solving a vehicle routing problem

Now you can use the Cloud Optimization API to solve a vehicle routing problem and get optimized routes.

Prepare your OptimizeToursRequest in a separate file or construct it in the code. The example below stores the request as a JSON file.

{
  "parent": "projects/${YOUR_GCP_PROJECT_ID}",
  "model": {
    "shipments": [
      {
        "deliveries": [
          {
            "arrivalLocation": {
              "latitude": 48.880942,
              "longitude": 2.323866
            },
            "duration": "250s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T01:06:40Z",
                "startTime": "1970-01-01T00:50:00Z"
              }
            ]
          }
        ],
        "loadDemands": {
          "weight": {
            "amount": "10"
          }
        },
        "pickups": [
          {
            "arrivalLocation": {
              "latitude": 48.874507,
              "longitude": 2.30361
            },
            "duration": "150s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T00:33:20Z",
                "startTime": "1970-01-01T00:16:40Z"
              }
            ]
          }
        ]
      },
      {
        "deliveries": [
          {
            "arrivalLocation": {
              "latitude": 48.88094,
              "longitude": 2.323844
            },
            "duration": "251s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T01:06:41Z",
                "startTime": "1970-01-01T00:50:01Z"
              }
            ]
          }
        ],
        "loadDemands": {
          "weight": {
            "amount": "20"
          }
        },
        "pickups": [
          {
            "arrivalLocation": {
              "latitude": 48.880943,
              "longitude": 2.323867
            },
            "duration": "151s",
            "timeWindows": [
              {
                "endTime": "1970-01-01T00:33:21Z",
                "startTime": "1970-01-01T00:16:41Z"
              }
            ]
          }
        ]
      }
    ],
    "vehicles": [
      {
        "loadLimits": {
          "weight": {
            "maxLoad": 50
          }
        },
        "endLocation": {
          "latitude": 48.86311,
          "longitude": 2.341205
        },
        "startLocation": {
          "latitude": 48.863102,
          "longitude": 2.341204
        },
        "costPerTraveledHour": 3600
      },
      {
        "loadLimits": {
          "weight": {
            "maxLoad": 60
          }
        },
        "endLocation": {
          "latitude": 48.86312,
          "longitude": 2.341215
        },
        "startLocation": {
          "latitude": 48.863112,
          "longitude": 2.341214
        },
        "costPerTraveledHour": 3600
      }
    ]
  }
}

Now, run the following code to perform your first call to the Cloud Fleet Routing service.

C++

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


#include "google/cloud/optimization/v1/fleet_routing_client.h"
#include "google/cloud/common_options.h"
#include "google/cloud/project.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " project-id destination\n"
              << "  destination is a GCS bucket\n";
    return 1;
  }
  // This quickstart loads an example model from a known GCS bucket. The service
  // solves the model, and writes the solution to the destination GCS bucket.
  std::string const source =
      "gs://cloud-samples-data/optimization-ai/async_request_model.json";
  auto const destination =
      std::string{"gs://"} + argv[2] + "/optimization_quickstart_solution.json";

  namespace gc = ::google::cloud;
  namespace optimization = ::google::cloud::optimization_v1;

  auto options = gc::Options{}.set<gc::UserProjectOption>(argv[1]);
  auto client = optimization::FleetRoutingClient(
      optimization::MakeFleetRoutingConnection(options));

  google::cloud::optimization::v1::BatchOptimizeToursRequest req;
  req.set_parent(gc::Project(argv[1]).FullName());
  auto& config = *req.add_model_configs();
  auto& input = *config.mutable_input_config();
  input.mutable_gcs_source()->set_uri(source);
  input.set_data_format(google::cloud::optimization::v1::JSON);
  auto& output = *config.mutable_output_config();
  output.mutable_gcs_destination()->set_uri(destination);
  output.set_data_format(google::cloud::optimization::v1::JSON);

  auto fut = client.BatchOptimizeTours(req);
  std::cout << "Request sent to the service...\n";
  auto resp = fut.get();
  if (!resp) throw std::move(resp).status();
  std::cout << "Solution written to: " << destination << "\n";

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

Java

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


import com.google.cloud.optimization.v1.FleetRoutingClient;
import com.google.cloud.optimization.v1.OptimizeToursRequest;
import com.google.cloud.optimization.v1.OptimizeToursResponse;
import com.google.protobuf.Duration;
import com.google.protobuf.TextFormat;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * This is an example to send a request to Cloud Fleet Routing synchronous API via Java API Client.
 * A sample sync_request.textproto file can be found in the resources folder.
 */
public class SyncApi {
  public static void callSyncApi() throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectParent = "projects/{YOUR_GCP_PROJECT_ID}";
    String modelPath = "YOUR_MODEL_PATH";
    callSyncApi(projectParent, modelPath);
  }

  public static void callSyncApi(String projectParent, String modelPath) throws Exception {
    int timeoutSeconds = 100;
    InputStream modelInputstream = new FileInputStream(modelPath);
    Reader modelInputStreamReader = new InputStreamReader(modelInputstream);
    OptimizeToursRequest.Builder requestBuilder =
        OptimizeToursRequest.newBuilder()
            .setTimeout(Duration.newBuilder().setSeconds(timeoutSeconds).build())
            .setParent(projectParent);
    TextFormat.getParser().merge(modelInputStreamReader, requestBuilder);
    FleetRoutingClient fleetRoutingClient = FleetRoutingClient.create();
    OptimizeToursResponse response = fleetRoutingClient.optimizeTours(requestBuilder.build());
    System.out.println(response.toString());
  }
}

Python

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


from google.cloud import optimization_v1

# TODO(developer): Uncomment these variables before running the sample.
# project_id= 'YOUR_PROJECT_ID'


def call_sync_api(project_id: str) -> None:
    """Call the sync api for fleet routing."""
    # Use the default credentials for the environment.
    # Change the file name to your request file.
    request_file_name = "resources/sync_request.json"
    fleet_routing_client = optimization_v1.FleetRoutingClient()

    with open(request_file_name) as f:
        # The request must include the `parent` field with the value set to
        # 'projects/{YOUR_GCP_PROJECT_ID}'.
        fleet_routing_request = optimization_v1.OptimizeToursRequest.from_json(f.read())
        fleet_routing_request.parent = f"projects/{project_id}"
        # Send the request and print the response.
        # Fleet Routing will return a response by the earliest of the `timeout`
        # field in the request payload and the gRPC timeout specified below.
        fleet_routing_response = fleet_routing_client.optimize_tours(
            fleet_routing_request, timeout=100
        )
        print(fleet_routing_response)
        # If you want to format the response to JSON, you can do the following:
        # from google.protobuf.json_format import MessageToJson
        # json_obj = MessageToJson(fleet_routing_response._pb)

Congratulations! You've sent your first request to Cloud Optimization.

How did it go?

Clean up

To avoid incurring charges to your Google Account for the resources used in this quickstart:

What's next

Find out more about our Cloud Optimization API Client Libraries.