Cloud Fleet Routing service is under specific service terms. See Service specific terms.

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 Cloud project. Learn how to check if billing is enabled on a 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. To provide access to your project, grant the following role(s) to your service account: Project > Owner.

      In the Select a role list, select a role.

      For additional roles, click Add another role and add each additional role.

    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 service account key. This variable only applies 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 Cloud project. Learn how to check if billing is enabled on a 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. To provide access to your project, grant the following role(s) to your service account: Project > Owner.

      In the Select a role list, select a role.

      For additional roles, click Add another role and add each additional role.

    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 service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Install the client library

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.

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

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

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

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

libraryDependencies += "com.google.cloud" % "google-cloud-optimization" % "1.0.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
        }
      },
      {
        "loadLimits": {
          "weight": {
            "maxLoad": 60
          }
        },
        "endLocation": {
          "latitude": 48.86312,
          "longitude": 2.341215
        },
        "startLocation": {
          "latitude": 48.863112,
          "longitude": 2.341214
        }
      }
    ]
  }
}

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

Java


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


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, "r") 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.