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:
Bash
1
export API_KEY=<YOUR-API-KEY>
Copied!
Run one of the following code snippets:
Python
Go
1
# Requires requests library
2
import datetime
3
import json
4
import os
5
import time
6
7
import requests
8
9
API_KEY = os.environ["API_KEY"]
10
URL = "https://api.cloud.nextmv.io/v0/run"
11
12
13
def solve(data: str) -> dict:
14
"""
15
Solve the problem using the Nextmv Cloud API.
16
"""
17
# Post job to Nextmv Cloud endpoint.
18
headers = {
19
"Authorization": f"Bearer {API_KEY}",
20
"Content-Type": "application/json",
21
"accept": "application/json",
22
}
23
response = requests.post(URL, data=data, headers=headers)
24
response.raise_for_status()
25
run_id = response.json()["runID"]
26
27
# Poll job status until it is finished or there is a timeout.
28
start, wait_time, wait_max, timeout = datetime.datetime.now(), 0.2, 5, 60
29
while True:
30
# Check for timeout.
31
if (datetime.datetime.now() - start).total_seconds() > timeout:
32
raise Exception(f"timed out after {timeout}")
33
34
# Get job status.
35
response = requests.get(
36
f"{URL}/{run_id}/status",
37
headers=headers,
38
)
39
response.raise_for_status()
40
status = response.json()["status"]
41
if status == "started" or status == "requested":
42
time.sleep(wait_time)
43
wait_time = min(wait_time * 2, wait_max)
44
elif status == "succeeded":
45
break
46
elif status == "timed_out":
47
raise Exception("no solution found within time limit")
48
elif status == "failed":
49
raise Exception("failed to solve the problem")
50
else:
51
raise Exception(f"unknown status occurred: {status}")
52
53
# Get the solution.
54
response = requests.get(f"{URL}/{run_id}/result", headers=headers)
55
response.raise_for_status()
56
return response.json()
57
58
59
def main():
60
data = json.dumps(
61
{
62
"vehicles": [
63
{
64
"id": "Vehicle 1",
65
"shift_start": "2021-01-01T12:00:00-05:00",
66
"speed": 10,
67
}
68
],
69
"stops": [
70
{
71
"id": "Binnenalster",
72
"position": {"lon": 9.992, "lat": 53.553},
73
},
74
{
75
"id": "Landungsbrücken",
76
"position": {"lon": 9.968, "lat": 53.545},
77
},
78
{
79
"id": "Hauptbahnhof Nord",
80
"position": {"lon": 10.006, "lat": 53.553},
81
},
82
],
83
}
84
)
85
86
# Solve the problem.
87
result = solve(data)
88
89
# Print the result.
90
print(json.dumps(result, ensure_ascii=False, indent=4))
91
92
93
if __name__ == "__main__":
94
main()
Copied!
1
package main
2
3
import (
4
"bytes"
5
"context"
6
"encoding/json"
7
"errors"
8
"fmt"
9
"io"
10
"io/ioutil"
11
"math"
12
"net/http"
13
"os"
14
"strings"
15
"time"
16
)
17
18
var apiKey = os.Getenv("API_KEY")
19
20
const url = "https://api.cloud.nextmv.io/v0/run"
21
22
// solve solves the problem using the Nextmv Cloud API.
23
func solve(data io.Reader) ([]byte, error) {
24
// Post job to Nextmv Cloud endpoint.
25
response, err := request("POST", url, data)
26
if err != nil {
27
return nil, err
28
}
29
runIdResp := &struct {
30
RunId string
31
}{}
32
if err = json.Unmarshal(response, runIdResp); err != nil {
33
return nil, err
34
}
35
runId := runIdResp.RunId
36
37
// Poll job status until it is finished or there is a timeout.
38
start, waitTime, waitMax, timeout := time.Now(), 0.2, 5., 60.
39
for {
40
// Check for timeout.
41
if time.Since(start).Seconds() > timeout {
42
return nil, fmt.Errorf("timed out after %f", timeout)
43
}
44
45
// Get job status.
46
response, err = request("GET", url+"/"+runId+"/status", nil)
47
if err != nil {
48
return nil, err
49
}
50
statusResp := &struct {
51
Status string
52
}{}
53
if err = json.Unmarshal(response, statusResp); err != nil {
54
return nil, err
55
}
56
status := statusResp.Status
57
if status == "started" || status == "requested" {
58
time.Sleep(time.Duration(waitTime) * time.Second)
59
waitTime = math.Min(waitTime*2, waitMax)
60
} else if status == "succeeded" {
61
break
62
} else if status == "timed_out" {
63
return nil, errors.New("no solution found within time limit")
64
} else if status == "failed" {
65
return nil, errors.New("failed to solve the problem")
66
} else {
67
return nil, fmt.Errorf("unknown status ocurred: %s", status)
68
}
69
}
70
71
// Get the solution.
72
response, err = request("GET", url+"/"+runId+"/result", nil)
73
if err != nil {
74
return nil, err
75
}
76
var out bytes.Buffer
77
if err := json.Indent(&out, response, "", " "); err != nil {
78
return nil, err
79
}
80
81
return out.Bytes(), nil
82
}
83
84
// request performs an HTTP request.
85
func request(method string, url string, data io.Reader) ([]byte, error) {
86
client := &http.Client{}
87
req, err := http.NewRequestWithContext(
88
context.Background(),
89
method,
90
url,
91
data,
92
)
93
if err != nil {
94
return nil, err
95
}
96
97
req.Header.Add("Authorization", "Bearer "+apiKey)
98
if method == "POST" {
99
req.Header.Add("Content-Type", "application/json")
100
req.Header.Add("accept", "application/json")
101
}
102
103
res, err := client.Do(req)
104
if err != nil {
105
return nil, err
106
}
107
108
body, err := ioutil.ReadAll(res.Body)
109
if err != nil {
110
return nil, err
111
}
112
113
return body, nil
114
}
115
116
func main() {
117
data := strings.NewReader(`{
118
"vehicles": [
119
{
120
"id": "Vehicle 1",
121
"shift_start": "2021-01-01T12:00:00-05:00",
122
"speed": 10.0
123
}
124
],
125
"stops": [
126
{
127
"id": "Binnenalster",
128
"position": {"lon": 9.992, "lat": 53.553}
129
},
130
{
131
"id": "Landungsbrücken",
132
"position": {"lon": 9.968, "lat": 53.545}
133
},
134
{
135
"id": "Hauptbahnhof Nord",
136
"position": {"lon": 10.006, "lat": 53.553}
137
}
138
]
139
}`)
140
141
// Solve the problem.
142
result, err := solve(data)
143
if err != nil {
144
panic(err)
145
}
146
147
// Print the result.
148
fmt.Println(string(result))
149
}
Copied!
You should obtain a response similar to this one:
JSON
1
{
2
// ...
3
"state": {
4
"vehicles": [
5
{
6
"id": "Vehicle 1",
7
"value": 274,
8
"travel_distance": 2742.867,
9
"travel_time": 274,
10
"route": [
11
{
12
"id": "Hauptbahnhof Nord",
13
"lon": 10.006,
14
"lat": 53.553,
15
"distance": 0,
16
"eta": "2021-01-01T12:00:00-05:00",
17
"ets": "2021-01-01T12:00:00-05:00",
18
"etd": "2021-01-01T12:00:00-05:00"
19
},
20
{
21
"id": "Binnenalster",
22
"lon": 9.992,
23
"lat": 53.553,
24
"distance": 924.819,
25
"eta": "2021-01-01T12:01:32-05:00",
26
"ets": "2021-01-01T12:01:32-05:00",
27
"etd": "2021-01-01T12:01:32-05:00"
28
},
29
{
30
"id": "Landungsbrücken",
31
"lon": 9.968,
32
"lat": 53.545,
33
"distance": 2742.867,
34
"eta": "2021-01-01T12:04:34-05:00",
35
"ets": "2021-01-01T12:04:34-05:00",
36
"etd": "2021-01-01T12:04:34-05:00",
37
}
38
]
39
}
40
],
41
"unassigned": [],
42
"value_summary": {
43
"value": 274,
44
"total_travel_distance": 2742.867,
45
"total_travel_time": 274,
46
"total_unassigned_penalty": 0,
47
"total_vehicle_initialization_costs": 0
48
}
49
},
50
// ...
51
}
Copied!
Export as PDF
Copy link