You are viewing Nextmv legacy docs. ⚡️ Go to latest docs ⚡️

Cloud

Code Snippets

Quick start guides to use the API in selected programming languages.

In this page we provide short guides on how to use the API in selected programming languages. Get your API key and set the following environment variable:

export API_KEY=<YOUR-API-KEY>
Copy

Run one of the following code snippets:

# Requires requests library
import datetime
import json
import os
import time

import requests

API_KEY = os.environ["API_KEY"]
URL = "https://api.cloud.nextmv.io/v0/run"


def solve(data: str) -> dict:
    """
    Solve the problem using the Nextmv Cloud API.
    """
    # Post job to Nextmv Cloud endpoint.
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
        "accept": "application/json",
    }
    response = requests.post(URL, data=data, headers=headers)
    response.raise_for_status()
    run_id = response.json()["runID"]

    # Poll job status until it is finished or there is a timeout.
    start, wait_time, wait_max, timeout = datetime.datetime.now(), 0.2, 5, 60
    while True:
        # Check for timeout.
        if (datetime.datetime.now() - start).total_seconds() > timeout:
            raise Exception(f"timed out after {timeout}")

        # Get job status.
        response = requests.get(
            f"{URL}/{run_id}/status",
            headers=headers,
        )
        response.raise_for_status()
        status = response.json()["status"]
        if status == "started" or status == "requested":
            time.sleep(wait_time)
            wait_time = min(wait_time * 2, wait_max)
        elif status == "succeeded":
            break
        elif status == "timed_out":
            raise Exception("no solution found within time limit")
        elif status == "failed":
            raise Exception("failed to solve the problem")
        else:
            raise Exception(f"unknown status occurred: {status}")

    # Get the solution.
    response = requests.get(f"{URL}/{run_id}/result", headers=headers)
    response.raise_for_status()
    return response.json()


def main():
    data = json.dumps(
        {
            "vehicles": [
                {
                    "id": "Vehicle 1",
                    "shift_start": "2021-01-01T12:00:00-05:00",
                    "speed": 10,
                }
            ],
            "stops": [
                {
                    "id": "Binnenalster",
                    "position": {"lon": 9.992, "lat": 53.553},
                },
                {
                    "id": "Landungsbrücken",
                    "position": {"lon": 9.968, "lat": 53.545},
                },
                {
                    "id": "Hauptbahnhof Nord",
                    "position": {"lon": 10.006, "lat": 53.553},
                },
            ],
        }
    )

    # Solve the problem.
    result = solve(data)

    # Print the result.
    print(json.dumps(result, ensure_ascii=False, indent=4))


if __name__ == "__main__":
    main()

Copy

You should obtain a response similar to this one:

{
  // ...
  "state": {
    "vehicles": [
      {
        "id": "Vehicle 1",
        "value": 274,
        "travel_distance": 2742.867,
        "travel_time": 274,
        "route": [
          {
            "id": "Hauptbahnhof Nord",
            "lon": 10.006,
            "lat": 53.553,
            "distance": 0,
            "eta": "2021-01-01T12:00:00-05:00",
            "ets": "2021-01-01T12:00:00-05:00",
            "etd": "2021-01-01T12:00:00-05:00"
          },
          {
            "id": "Binnenalster",
            "lon": 9.992,
            "lat": 53.553,
            "distance": 924.819,
            "eta": "2021-01-01T12:01:32-05:00",
            "ets": "2021-01-01T12:01:32-05:00",
            "etd": "2021-01-01T12:01:32-05:00"
          },
          {
            "id": "Landungsbrücken",
            "lon": 9.968,
            "lat": 53.545,
            "distance": 2742.867,
            "eta": "2021-01-01T12:04:34-05:00",
            "ets": "2021-01-01T12:04:34-05:00",
            "etd": "2021-01-01T12:04:34-05:00",
          }
        ]
      }
    ],
    "unassigned": [],
    "value_summary": {
      "value": 274,
      "total_travel_distance": 2742.867,
      "total_travel_time": 274,
      "total_unassigned_penalty": 0,
      "total_vehicle_initialization_costs": 0
    }
  },
  // ...
}
Copy

Page last updated