Skip to main content

Sample API Requests

Contents

The sample code below is provided as a way to demonstrate 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);
    }
  }
};

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);
}

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;
    }
}

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 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 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);
}
Last updated January 25, 2023.
Contents