Use the REST API to send requests

This quickstart shows how to solve the VRP example by sending asynchronous REST API requests to the Cloud Fleet Routing service. The REST API sends JSON payloads over REST. These examples use Google's Distance Matrix API to compute the distance between visit locations, so a Google Maps API key is required.

Before you begin

To send REST API requests to the API, follow the setup instructions in the Before you begin guide to authenticate your environment.

Send REST API requests

The following script sends the request in a file request.json to the :optimizeTours method of the Cloud Fleet Routing service.

The following shows an example request body:

{
  "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
      }
    ]
  }
}

Make sure to update the ${YOUR_GCP_PROJECT_ID} placeholders with your project ID,

Python
import sys
import requests

import google.auth
from google.auth.transport import requests as google_requests

def main(request_file_name):
  # Generate an OAuth2 access token using the default application credentials.
  credentials, project = google.auth.default()
  google_request = google_requests.Request()
  credentials.refresh(google_request)
  url = 'https://cloudoptimization.googleapis.com/v1/projects/'
  url += '{project}:optimizeTours?access_token={access_token}'.format(
    project=project,
    access_token=credentials.token
  )

  # Get the data.
  with open(request_file_name, 'r') as f:
      request = f.read()

  # Cloud Fleet Routing will return a response by the earliest of the `timeout`
  # field in the request payload and the server timeout specified below.
  headers = {
    'Content-Type': 'application/json',
    'X-Goog-User-Project': project,
    'X-Server-Timeout': '200'
  }
  # Send the request and print the response.
  response = requests.post(url, data=request, headers=headers)
  print(response.text)


if __name__ == '__main__':
  if len(sys.argv) > 1:
    main(sys.argv[1])
  else:
    print('You must include the request file as an argument.')
  • Save the script as send_http_request_py.txt, and save the JSON file as request.json in the same directory.
  • Authenticate your environment using the instructions in the Before You Begin guide.
  • Replace ${YOUR_GCP_PROJECT_ID} with your Google Cloud project ID in the request.
  • In your terminal, navigate to the directory containing the files and enter
    python -m send_http_request request.json
    Note that the command includes the name of the request file as an argument.
  • Curl
    curl -X POST \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $(YOUR_ACCESS_TOKEN)"
      -H "x-goog-user-project: ${YOUR_GCP_PROJECT_ID}"
      -d @request.json \
      https://cloudoptimization.googleapis.com/v1/projects/${YOUR_GCP_PROJECT_ID}:optimizeTours
    
  • Get your access token by entering gcloud auth print-access-token in your terminal. Save the JSON file as request.json in the same directory.
  • Replace ${YOUR_GCP_PROJECT_ID} with your Google Cloud project ID in both code and request.
  • In your terminal, run the Curl script. Note that the command includes the name of the request file as an argument.
  • Response

    The API will return the JSON representation of OptimizeToursResponse. The following shows the response to the preceding REST API request.

    {
      "routes": [
        {
          "vehicleStartTime": "1970-01-01T00:02:11Z",
          "vehicleEndTime": "1970-01-01T01:15:34Z",
          "visits": [
            {
              "isPickup": true,
              "startTime": "1970-01-01T00:16:40Z",
              "detour": "0s",
              "arrivalLoads": [
                {
                  "type": "weight"
                }
              ]
            },
            {
              "shipmentIndex": 1,
              "isPickup": true,
              "startTime": "1970-01-01T00:27:35Z",
              "detour": "725s",
              "arrivalLoads": [
                {
                  "type": "weight",
                  "value": "10"
                }
              ]
            },
            {
              "startTime": "1970-01-01T00:50:00Z",
              "detour": "1345s",
              "arrivalLoads": [
                {
                  "type": "weight",
                  "value": "30"
                }
              ]
            },
            {
              "shipmentIndex": 1,
              "startTime": "1970-01-01T00:58:43Z",
              "detour": "1444s",
              "arrivalLoads": [
                {
                  "type": "weight",
                  "value": "20"
                }
              ]
            }
          ],
          "travelSteps": [
            {
              "duration": "869s",
              "distanceMeters": 4243
            },
            {
              "duration": "505s",
              "distanceMeters": 2480
            },
            {
              "duration": "0s"
            },
            {
              "duration": "273s",
              "distanceMeters": 986
            },
            {
              "duration": "760s",
              "distanceMeters": 3099
            }
          ],
          "vehicleDetour": "4403s",
          "endLoads": [
            {
              "type": "weight"
            }
          ],
          "transitions": [
            {
              "travelDuration": "869s",
              "travelDistanceMeters": 4243,
              "loads": [
                {
                  "type": "weight"
                }
              ]
            },
            {
              "travelDuration": "505s",
              "travelDistanceMeters": 2480,
              "loads": [
                {
                  "type": "weight",
                  "value": "10"
                }
              ]
            },
            {
              "travelDuration": "0s",
              "loads": [
                {
                  "type": "weight",
                  "value": "30"
                }
              ]
            },
            {
              "travelDuration": "273s",
              "travelDistanceMeters": 986,
              "loads": [
                {
                  "type": "weight",
                  "value": "20"
                }
              ]
            },
            {
              "travelDuration": "760s",
              "travelDistanceMeters": 3099,
              "loads": [
                {
                  "type": "weight"
                }
              ]
            }
          ]
        },
        {
          "vehicleIndex": 1,
          "vehicleStartTime": "1970-01-01T00:00:00Z",
          "vehicleEndTime": "1970-01-01T00:00:00Z",
          "vehicleDetour": "0s"
        }
      ]
    }
    

    For a description of the response, see Response to the request in the VRP example page.