Single courier routing

Request to this resource builds a route for the courier, accounting for traffic and delivery periods.

Step 1. Send a request to build a route

Request:

curl -X POST "https://courier.yandex.ru/vrs/api/v1/add/svrp?apikey=<your API key>" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"depot\": {\"time_window\": \"07:00:00-23:59:59\",\"point\": {\"lat\": 55.751245,\"lon\": 37.618424}},\"locations\": [{\"id\":1,\"time_window\": \"07:00:00-23:59:59\",\"point\": {\"lat\": 55.751245,\"lon\": 37.618424}}],\"vehicle\": {\"id\": 0}, \"options\":{\"time_zone\": 3}}"

The request must contain the API key you obtained. If you don't have a key, submit a connection request.

Response:

The server response contains information about the request processing status.

{
    "id": "45c206a8-6fac1ab2-65d71a0c-cc3891be",
    "status": {
        "estimate": 1699427501.087656,
        "queued": 1699427496.986748
    },
    "yt_operations": [],
    "message": "Task queued"
}

Save the resulting id to use it in the next step.

You can send a request to build a route using the requests library:

#!/usr/bin/env python2.7
import requests
import time
import datetime

API_KEY = '<your API key>'
API_ROOT_ENDPOINT = 'https://courier.yandex.ru/vrs/api/v1'

# Create the request body that includes the depot, delivery locations, vehicle, and settings.
payload = {
    'depot': {'id': 0, 'time_window': '07:00-23:59', 'point': {'lat': 55.733777, 'lon': 37.588118}},
    'locations': [
        {'id': 1, 'time_window': '09:00-20:00', 'point': {'lat': 55.684872, 'lon': 37.595965}},
        {'id': 2, 'time_window': '15:00-20:00', 'point': {'lat': 55.739796, 'lon': 37.689102}},
        {'id': 3, 'time_window': '12:00-15:00', 'point': {'lat': 55.809657, 'lon': 37.520314}},
        {'id': 4, 'time_window': '09:00-15:00', 'point': {'lat': 55.744764, 'lon': 37.558224}},
        {'id': 5, 'time_window': '15:00-20:00', 'point': {'lat': 55.788563, 'lon': 37.670101}},
    ],
    'vehicle': {'id': 0},
    'options':{'time_zone': 3}
}

# Send the request and receive the task ID.
response = requests.post(
    API_ROOT_ENDPOINT + '/add/svrp',
    params={'apikey': API_KEY}, json=payload)

You can send the request using the "request" module:

var request = require('request');

// Create the request body that includes the depot, delivery locations, vehicle, and settings.
var payload = {
    'depot': {'id': 0, 'time_window': '07:00-23:59', 'point': {'lat': 55.733777, 'lon': 37.588118}},
    'locations': [
        {'id': 1, 'time_window': '09:00-20:00', 'point': {'lat': 55.684872, 'lon': 37.595965}},
        {'id': 2, 'time_window': '15:00-20:00', 'point': {'lat': 55.739796, 'lon': 37.689102}},
        {'id': 3, 'time_window': '12:00-15:00', 'point': {'lat': 55.809657, 'lon': 37.520314}},
        {'id': 4, 'time_window': '09:00-15:00', 'point': {'lat': 55.744764, 'lon': 37.558224}},
        {'id': 5, 'time_window': '15:00-20:00', 'point': {'lat': 55.788563, 'lon': 37.670101}},
    ],
    'vehicle': {'id': 0},
    'options':{'time_zone': 3}
};

const API_KEY = '<your API key>';
const API_ROOT_ENDPOINT = 'https://courier.yandex.ru/vrs/api/v1'

// Send the request and receive the task ID.
function sendRequest(payload) {
    var url = API_ROOT_ENDPOINT + '/add/svrp?apikey=' + API_KEY;
    var options = {
        body: JSON.stringify(payload),
        headers: {'Content-Type': 'application/json'}
    }

    return new Promise(function(resolve, reject) {
        request.post(url, options, function(error, response, body) {
            if (error) { reject(error); }
            else {
                var code = response.statusCode;
                if (code == 201 || code == 202) {
                    resolve(JSON.parse(body).id);
                } else {
                    reject(body);
                }
            }
        })
    });
}

function handleError(error) {
    console.log('Error:', error);
}

// sendRequest(payload)
//     .catch(handleError);

Information about the request body is available on the service page.

Step 2. Get the processing result

You can obtain the built route by sending a GET request to the service.

Request:

curl -X GET "https://courier.yandex.ru/vrs/api/v1/result/svrp/45c206a8-6fac1ab2-65d71a0c-cc3891be"

Response:

If the route was built, the response will contain information about the route. Otherwise, the response will contain information about the request processing status.

# Wait for the response.
poll_stop_codes = {
    requests.codes.ok,
    requests.codes.gone,
    requests.codes.internal_server_error
}

# Request the server whether the route optimization result is ready using the ID that you received earlier.
if response.status_code == requests.codes.accepted:
    request_id = response.json()['id']
    poll_url = '{}/result/svrp/{}'.format(API_ROOT_ENDPOINT, request_id)

    response = requests.get(poll_url)
    while response.status_code not in poll_stop_codes:
        time.sleep(1)
        response = requests.get(poll_url)

    # Output the data in a custom format.
    if response.status_code != 200:
        print 'Error {}: {}'.format(response.text, response.status_code)
    else:
        print 'Route optimization completed'
        print ''

        for route in response.json()['result']['routes']:
            print 'Vehicle {} route: {:.2f}km'.format(
                route['vehicle_id'], route['metrics']['total_transit_distance_m'] / 1000)

            # Output the route in text format.
            for waypoint in route['route']:
                print '  {type} {id} at {eta}, {distance:.2f}km driving '.format(
                    type=waypoint['node']['type'],
                    id=waypoint['node']['value']['id'],
                    eta=str(datetime.timedelta(seconds=waypoint['arrival_time_s'])),
                    distance=waypoint['transit_distance_m'] / 1000)

            # Output the route as a link to Yandex Maps.
            yamaps_url = 'https://yandex.ru/maps/?mode=routes&rtext='
            for waypoint in route['route']:
                point = waypoint['node']['value']['point']
                yamaps_url += '{}%2c{}~'.format(point['lat'], point['lon'])

            print ''
            print 'See route on Yandex.Maps:'
            print yamaps_url
// Request the server whether the route optimization result is ready using the ID that you received earlier.
function pollResponse(requestId) {
    function delay(t) {
        return new Promise(function(resolve) {
            setTimeout(resolve, t);
        });
    }

    function poller(resolve, reject) {
        function run() {
            let url = API_ROOT_ENDPOINT + '/result/svrp/' + requestId;

            request.get(url, function(error, response, body) {
                if (error) { reject(error); }
                else {
                    let result = JSON.parse(body);
                    let code = response.statusCode;
                    if (code != 200 && code != 410 && code != 500) {
                        delay(500).then(run);
                    } else {
                        if (code == 200) {
                            resolve(JSON.parse(body));
                        } else {
                            reject(body);
                        }
                    }
                }
            });
        }
        run();
    }

    return new Promise(poller);
}

// Output the data in a custom format.
function printResponse(response) {
    console.log('Route optimization completed\n')

    for (route of response.result.routes) {
        let distance_km =
            (route.metrics.total_transit_distance_m / 1000).toFixed(2)

        console.log(`Vehicle ${route.vehicle_id} route: ${distance_km}km`);

        // Output the route in text format.
        for (waypoint of route.route) {
            let type = waypoint.node.type;
            let id = waypoint.node.value.id;
            let eta = new Date(waypoint.arrival_time_s * 1000).toISOString().substr(11, 8);
            let distance_km = (waypoint.transit_distance_m / 1000).toFixed(2);

            console.log(`  ${type} ${id} at ${eta}, ${distance_km}km driving `);
        }

        // Output the route as a link to Yandex Maps.
        let yamaps_url = 'https://yandex.ru/maps/?mode=routes&rtext='
        for (waypoint of route.route) {
            let point = waypoint.node.value.point;
            yamaps_url += `${point.lat}%2c${point.lon}~`;
        }

        console.log('\nSee route on Yandex.Maps:\n', yamaps_url)
    }
}

// Asynchronous execution of functions.
sendRequest(payload)
    .then(pollResponse)
    .then(printResponse)
    .catch(handleError);
Contact support