Skip to main content

Sample API Requests

Contents

The sample code below demonstrates possible ways to call our RESTful APIs. We do not recommend using the samples “as is” in your projects. These samples cannot account for differences in the environments in which developers might use them—for example, things such as out-of-date libraries, changes in language versions, etc. While the Trimble Maps support team can help with general questions about integrating our APIs, it cannot assist with specific coding-related issues.

GET Requests

Typically a GET request is made to retrieve/read data from the server. Here are some sample requests to GET service endpoints as they might be implemented in a few popular languages.

GET JavaScript

function dictToParamString(obj) {
  var str = [];
  for (var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
  return str.join("&");
}

reqhttp = new XMLHttpRequest();
var url = "https://singlesearch.alk.com/na/api/search?";

var params = {
  query: "37.892845, -85.974742"
};

var urlQuery = url + dictToParamString(params);
reqhttp.open("GET", urlQuery, true);
reqhttp.setRequestHeader("Content-type", "application/json");
reqhttp.setRequestHeader("Authorization", "**YOUR API KEY HERE**");
reqhttp.responseType = "arraybuffer";

reqhttp.onreadystatechange = function () {
  // Call a function when the state changes.
  if (reqhttp.readyState == 4 && reqhttp.status == 200) {
    var res = reqhttp.response;
    if (res) {
      var uInt8Array = new Uint8Array(res);
      var i = uInt8Array.length;
      var binaryString = new Array(i);
      while (i--) {
        binaryString[i] = String.fromCharCode(uInt8Array[i]);
      }
      var data = binaryString.join("");

      console.log(data);
    }
  }
};

function doFunction() {
    reqhttp.send();
}

GET Java

package com.example;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class App
{
    private static String encodeValue(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getCause());
        }
    }

    public static void main( String[] args )
    {
        String apiKeyVal = "**YOUR API KEY HERE**";
        String query = "query=" + encodeValue("37.892845, -85.974742");
        String address = "https://singlesearch.alk.com/na/api/search?";
        String urlFormatted = address + query;
        URL url;
        StringBuffer content = new StringBuffer();
        try {
            url = new URL(urlFormatted);
            HttpURLConnection connection;
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Authorization", apiKeyVal);
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setReadTimeout(15 * 1000);
            connection.connect();
            String type = connection.getContentType();
            if(type != null)
            {
                BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(content);
    }
}

GET C#

using System.Net;
using System.Collections.Generic;
using System.Web;

namespace Example;
class Program
{
    private static HttpRequestMessage BuildRequest(HttpMethod method, string serviceURL, Dictionary<string, string> queryParams, Dictionary<string, string> headers)
    {
        var url = string.Format("{0}?{1}", serviceURL,
        string.Join("&",
            queryParams.Select(kvp =>
                string.Format("{0}={1}", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value)))));

        Uri requestUri = new Uri(url);
        var request = new HttpRequestMessage { Method = method, RequestUri = requestUri };

        foreach (string k in headers.Keys)
        {
            request.Headers.Add(k, headers[k]);
        }
        return request;
    }

    static async Task<int> Main(string[] args)
    {
        HttpClient _client = new HttpClient();

        String address = "https://singlesearch.alk.com/na/api/search";

        Dictionary<string, string> queryParams = new Dictionary<string, string>(){
            {"query", "37.892845, -85.974742"}
        };

        Dictionary<string, string> headers = new Dictionary<string, string>(){
            {"Authorization", "YOUR_API_KEY_HERE"}
        };
        var request = BuildRequest(HttpMethod.Get, address, queryParams, headers);
        var cts = new CancellationTokenSource();
        cts.CancelAfter(20000);
        try
        {
            var response = await _client.SendAsync(request, cts.Token);
            if(response.StatusCode == HttpStatusCode.OK)
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            else
                Console.WriteLine(String.Format("Service returned {0} status", response.StatusCode));
        }
        catch(WebException ex)
        {
            Console.WriteLine("Web Request Failed!");
            Console.WriteLine(ex);
        }
        catch (TaskCanceledException ex)
        {
            if (cts.Token.IsCancellationRequested)
                Console.WriteLine("Web Request Timeout!");
            else
            {
                Console.WriteLine("Web Request Failed!");
                Console.WriteLine(ex);
            }
        }
        return 0;
    }
}

GET Python

import requests
from urllib.parse import urlencode
import backoff

def getHeaders(apikey):
    headers = {
        'Authorization': f'{apikey}',
        'Accept': 'application/json',
        'Content-type': 'application/json'
    }
    return headers

@backoff.on_exception(backoff.expo,
                      requests.exceptions.ReadTimeout, max_time=10)
def makeRequest(url, headers, params):
    response = requests.get(url, headers=headers, params=params, timeout=10)
    return response

def main():
    query = '37.892845, -85.974742'
    region = 'na'
    apikey = '**YOUR API KEY HERE**'
    try:
        url = f'https://singlesearch.alk.com/{region}/api/search'
        params = {
            'query': query,
            'includeTrimblePlaceIds': 'true'
        }
        headers = getHeaders(apikey)
        response = makeRequest(url, headers, urlencode(params))
        jsonobj = response.json()
        print(jsonobj)
    except requests.exceptions.ReadTimeout as e:
        print(f"Request Timed out after trying 10 times with an exponential backoff: {e}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")

if __name__ == "__main__":
    main()

POST Requests

Typically a POST request is used to submit/create an object/resource on the server. Here are some sample requests to POST service endpoints as they might be implemented in a few popular languages.

POST JavaScript

reqhttp = new XMLHttpRequest();
var url = "https://pcmiler.alk.com/APIs/REST/v1.0/Service.svc/route/routeReports?dataVersion=Current";
reqhttp.open("POST", url, true);
reqhttp.setRequestHeader("Content-type", "application/json");
reqhttp.setRequestHeader("Authorization", "**YOUR API KEY HERE**");
reqhttp.responseType = "arraybuffer";

reqhttp.onreadystatechange = function () {
  //Call a function when the state changes.
  if (reqhttp.readyState == 4 && reqhttp.status == 200) {
    var res = reqhttp.response;
    if (res) {
      var uInt8Array = new Uint8Array(res);
      var i = uInt8Array.length;
      var binaryString = new Array(i);
      while (i--) {
        binaryString[i] = String.fromCharCode(uInt8Array[i]);
      }
      var data = binaryString.join("");

      console.log(data);
    }
  }
};

var postData =
  '{ "ReportRoutes": [{"RouteId": "test", "Stops": [{"Address": {"Zip": "08540"},"Label": "Trimble Maps"}, {"Address": {"Zip": "90266"},"Label": "Manhattan Beach"}], "ReportTypes": [{"__type": "MileageReportType:http://pcmiler.alk.com/APIs/v1.0","THoursWithSeconds": false}]}]}';

doFunction();
function doFunction() {
  reqhttp.send(postData);
}

POST Java

package com.example;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class App
{
    private static String encodeValue(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getCause());
        }
    }

    public static void main( String[] args )
    {
        String apiKeyVal = "**YOUR API KEY HERE**";
        String urlFormatted = "https://pcmiler.alk.com/APIs/REST/v1.0/Service.svc/route/routeReports?dataVersion=Current";
        String postData = "{ \"ReportRoutes\": [{\"RouteId\": \"test\", \"Stops\": [{\"Address\": {\"Zip\": \"08540\"},\"Label\": \"Trimble Maps\"}, {\"Address\": {\"Zip\": \"90266\"},\"Label\": \"Manhattan Beach\"}], \"ReportTypes\": [{\"__type\": \"MileageReportType:http://pcmiler.alk.com/APIs/v1.0\",\"THoursWithSeconds\": false}]}]}";
        byte[] out = postData.getBytes(StandardCharsets.UTF_8);
        try {
            URL url = new URL(urlFormatted);
            HttpURLConnection connection;
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Authorization", apiKeyVal);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Content-Length", Integer.toString(out.length));
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setReadTimeout(15 * 1000);
            OutputStream os = connection.getOutputStream();
            os.write(out);
            os.flush();

            if (connection.getResponseCode() != 200)
            if (connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "+ connection.getResponseCode());
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println(response.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

POST C#

using System.Net;
using System.Collections.Generic;
using System.Web;
using System.Text;

namespace dotnet;
class Program
{
    private static HttpRequestMessage BuildRequest(HttpMethod method, string serviceURL, Dictionary<string, string> queryParams, string data, Dictionary<string, string> headers)
    {
        var url = string.Format("{0}?{1}", serviceURL,
        string.Join("&",
            queryParams.Select(kvp =>
                string.Format("{0}={1}", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value)))));

        Uri requestUri = new Uri(url);
        var request = new HttpRequestMessage { Method = method, RequestUri = requestUri };
        request.Content = new StringContent(data, Encoding.UTF8, "application/json");
        foreach (string k in headers.Keys)
        {
            request.Headers.Add(k, headers[k]);
        }
        return request;
    }

    static async Task<int> Main(string[] args)
    {
        HttpClient _client = new HttpClient();

        String address = "https://pcmiler.alk.com/APIs/REST/v1.0/Service.svc/route/routeReports";

        Dictionary<string, string> queryParams = new Dictionary<string, string>(){
            {"dataVersion", "Current"}
        };

        var postData = "{ \"ReportRoutes\": [{\"RouteId\": \"test\", \"Stops\": [{\"Address\": {\"Zip\": \"08540\"},\"Label\": \"Trimble Maps\"}, {\"Address\": {\"Zip\": \"90266\"},\"Label\": \"Manhattan Beach\"}], \"ReportTypes\": [{\"__type\": \"MileageReportType:http://pcmiler.alk.com/APIs/v1.0\",\"THoursWithSeconds\": false}]}]}";

        Dictionary<string, string> headers = new Dictionary<string, string>(){
            {"Authorization", "**YOUR API KEY HERE**"},
            {"ContentType", "application/json"}
        };
        var request = BuildRequest(HttpMethod.Post, address, queryParams, postData, headers);
        var cts = new CancellationTokenSource();
        cts.CancelAfter(20000);
        try
        {
            var response = await _client.SendAsync(request, cts.Token);
            if(response.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
            else
            {
                Console.WriteLine(String.Format("Service returned {0} status", response.StatusCode));
            }
        }
        catch(WebException ex)
        {
            Console.WriteLine("Web Request Failed!");
            Console.WriteLine(ex);
        }
        catch (TaskCanceledException ex)
        {
            if (cts.Token.IsCancellationRequested)
            {
                Console.WriteLine("Web Request Timeout!");
            }
            else
            {
                Console.WriteLine("Web Request Failed!");
                Console.WriteLine(ex);
            }
        }
        return 0;
    }
}

POST Python

import requests
from urllib.parse import urlencode
import backoff
import json

def getHeaders(apikey):
    headers = {
        'Authorization': f'{apikey}',
        'Accept': 'application/json',
        'Content-type': 'application/json'
    }
    return headers

@backoff.on_exception(backoff.expo,
                      requests.exceptions.ReadTimeout, max_time=10)
def makeRequest(url, headers, params, postData):
    response = requests.post(url, headers=headers, params=params, data=postData, timeout=10)
    return response

def main():
    postData = {
        "ReportRoutes": [{
            "RouteId": "test",
            "Stops": [
                {
                    "Address": {
                        "Zip": "08540"
                    },
                    "Label": "Trimble Maps"
                },
                {
                    "Address": {
                        "Zip": "90266"
                    },
                    "Label": "Manhattan Beach"
                }
            ],
            "ReportTypes": [
                {
                    "__type": "MileageReportType:http://pcmiler.alk.com/APIs/v1.0",
                    "THoursWithSeconds": False
                }
            ]
        }]
    }
    apikey = '**YOUR API KEY HERE**'
    try:
        url = f'https://pcmiler.alk.com/APIs/REST/v1.0/Service.svc/route/routeReports'
        params = {
            'dataVersion': 'current'
        }
        postData = postData
        headers = getHeaders(apikey)
        response = makeRequest(url, headers, urlencode(params), postData=json.dumps(postData))
        jsonobj = response.json()
        print(jsonobj)
    except requests.exceptions.ReadTimeout as e:
        print(f"Request Timed out after trying 10 times with an exponential backoff: {e}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")

if __name__ == "__main__":
    main()
Last updated May 13, 2024.
API Endpoint:

Contents